1

Template structure

It mainly includes four parts:

  • preset.json
  • prompts.js
  • generator/index.js
  • template/

preset.json

In preset.json is a JSON object containing predefined options and plug-ins required to create a new project, so that users do not need to select them in the command prompt, referred to as presets;

prompts.js

Interactively inform vue create what is needed, which is the information that is customized according to the user's needs.

For the definition format, refer to the array of Inquirer question format (Inquirer official document)

generator.js

generator.js exports a function, this function receives three parameters

  1. An instance of GeneratorAPI

    1. Provide a series of APIs to control the final output directory structure and content
    2. Custom templates must use the render() method of GeneratorAPI
  2. User-defined setting options

    1. That is: the answer provided by the user to the question in prompts.js
  3. The entire preset preset information

Simple custom template example

Create project

Manually create the directory structure:

|- vue-template
  |- generator
    |- index.js
  |- preset.json
  |- prompts.js

Get the preset.json template

First use vue create to create a project, then save your preset information, and find the preset information in the specified directory:

# Unix
~/.vuerc
# windows
C://用户/<username>/.vuerc
{
  "useTaobaoRegistry": false, 
  "latestVersion": "4.5.14", 
  "lastChecked": 1634820758861, 
  "packageManager": "npm",
  "presets": {
    "v2": {
      "useConfigFiles": true,
      "plugins": {
        "@vue/cli-plugin-babel": {},
        "@vue/cli-plugin-typescript": {
          "classComponent": false,
          "useTsWithBabel": true
        },
        "@vue/cli-plugin-router": {
          "historyMode": false
        },
        "@vue/cli-plugin-vuex": {},
        "@vue/cli-plugin-eslint": {
          "config": "prettier",
          "lintOn": [
            "save",
            "commit"
          ]
        }
      },
      "vueVersion": "2",
      "cssPreprocessor": "dart-sass"
    }
  }
}

Among them, presets are the preset information, v2 is the alias for saving the presets, and what our preset.json needs is the value of v2, so the content in preset.json is like this

{
  "useConfigFiles": true,
  "plugins": {
    "@vue/cli-plugin-babel": {},
    "@vue/cli-plugin-typescript": {
      "classComponent": false,
      "useTsWithBabel": true
    },
    "@vue/cli-plugin-router": {
      "historyMode": false
    },
    "@vue/cli-plugin-vuex": {},
    "@vue/cli-plugin-eslint": {
      "config": "prettier",
      "lintOn": [
        "save",
        "commit"
      ]
    }
  },
  "vueVersion": "2",
  "cssPreprocessor": "dart-sass"
}

Create Q&A prompts.js

module.exports = []

prompts.js We can not provide questions, just export an empty array;

Create project template generator generator

# generator/index.js
module.exports = (api, options, rootOptions) => {
  api.extendPackage({
    # 扩展pkg#scripts
    scripts: {
      "serve": "vue-cli-service serve",
      "build": "vue-cli-service build",
      "lint": "vue-cli-service lint"
    }, 
    # 扩展pkg#dependencies
    dependencies: {
      "vue": "^2.6.11"
    }, 
    # 扩展pkg#devDependencies
    devDependencies: {
      "@babel/core": "^7.11.4",
      "@babel/preset-env": "^7.11.0",
      "@vue/cli-service": "~4.5.0",
      "sass": "^1.26.10",
      "sass-loader": "^8.0.2"
    }
  });
  # 复制template模版
  api.render('../template');
};

Private dependency

If you store the configuration .vuerc, and useTaobaoRegistry = true, when you create the project through the template, it will report that the private dependency cannot be found. This requires us to check the global configuration items before creating the project.

  var vuerc = shell.exec('vue config', { silent:true }).stdout
  var deleteConfigKey = 'useTaobaoRegistry'
  if (new RegExp(deleteConfigKey).test(vuerc)) {
    shell.exec(`vue config --set ${deleteConfigKey} false`, { silent:true })
  }
  child.execSync(
    `vue create --preset multi-act --clone ${projectName}`,
    {
      stdio: 'inherit'
    }
  );
  fs.ensureDirSync(`${projectName}/${Configure.BaseUri}`)

Create a template

Finally, just copy the project template to the template, and then delete the package.json file.
For files beginning with ., change to _, for example. eslintrc.js ==》_eslintrc.js.

Because files starting with. Will be ignored when uploading and pulling in Git.

Default template structure

If there are more Vue-Cli default template files in the project, you can use the following method to delete the default template

  // 存储vue-cli3 默认目录
  const defaultDirs = []
  api.render(files => {
    Object.keys(files)
      .filter(path => path.startsWith('src/') || path.startsWith('public/'))
      .forEach(path => {
        defaultDirs.push(path)
        delete files[path]
      })
  })
  api.render('../template')
  // 删除 vue-cli3 默认目录
  api.postProcessFiles(files => {
    defaultDirs.forEach(path => delete files[path])
  })

debugging

Use vue create --preset <relativePath/vue-template> <project_name> to create the project.

deploy

You can choose to deploy the template to github and gitlab.

# GitHub 
$ vue create --preset <username>/<repo> <vue_project_name> 
 
# GitLab 私有服务器 
$ vue create --preset gitlab:<my-gitlab-server.com>:<group>/<project_name> --clone <vue_project_name> 

# 通用
$ vue create --preset direct:<url> --clone <vue_project_name>

For specific template parameters, please refer to download-git-repo

Reference project:

Reference documents:


米花儿团儿
1.3k 声望75 粉丝