preface

When we use Vue to develop projects, VUE-CLI gives us a set of project templates out of the box, eliminating the need to configure WebPack. However, since vuE-CLI is open to all developers, it provides a very basic project template. When we use this template to develop, we usually need to introduce common tripartite libraries such as AXIos Element-UI, and configure some common Webpack optimization configurations. But when our new project again, these common things need to be copied again, again as a front man, this kind of repeated labor, it is difficult to accept, so we hope can define their own project template, when we open a new project, use your own template directly, the content of the commonly used we are configured.

Then iframe architecture micro front-end combat also mentioned to make father and son projects into common project template, convenient for new project development, so this article will talk about how to customize vuE-CLI project template

Project address: github.com/luokaibin/i…

3 files and a template

Customize a VUE-CLI project template. It’s as simple as can be, and the main requirement is to provide 3 files presection.json prompts. Js generated. js and a template.

In order to make your templates available on any device, it is recommended to put your templates on Github, so the first step is to create a project on Github, and then pull your project down. After pulling it down, create the three files and a folder in the project

├── Template ├─ generating.js ├── recall. Json ├.jsCopy the code

What do these three documents do

preset.json

When you use the vue create command to create a project, you will be prompted to save your options. When you create a project next time, you can directly select the information you selected last time. Json is used for this preset information, preset for short; Official Documentation Preset

prompts.js

Prompts. Js. When you use the vue create command to create an item, it asks you if you use a Bable, etc. Prompts. Js will eventually need to export an array that meets the format of an Inquirer question, the Inquirer’s official document

generator.js

Generator.js exports a function that takes three arguments

  1. aGeneratorAPIExample: Custom templates must be usedGeneratorAPIrender()methods
  2. The generator option for this plug-in, which is the user pairprompts.jsThe answer to the question
  3. The preset (presets.foo) will be passed in as the third argument.

generator.jsThe official documentation

Implement a custom template for a simple version

The first step

Create a project with vue create and save your preset information to ~/. Vuerc and copy preset information you just saved to preset. Json

Open.vuerc and you might see data that looks like this

{
  "useTaobaoRegistry": true."latestVersion": "Holdings"."lastChecked": 1584603622605."packageManager": "npm"."presets": {
    "test": {
      "useConfigFiles": true."plugins": {
        "@vue/cli-plugin-babel": {},
        "@vue/cli-plugin-router": {
          "historyMode": true
        },
        "@vue/cli-plugin-vuex": {},
        "@vue/cli-plugin-eslint": {
          "config": "prettier"."lintOn": [
            "save"."commit"]}},"cssPreprocessor": "less"}}}Copy the code

Presets hold your preset information, test is the alias you want to save the preset, and preset. Json is needed for test, so preset

{
  "useConfigFiles": true."plugins": {
    "@vue/cli-plugin-babel": {},
    "@vue/cli-plugin-router": {
      "historyMode": true
    },
    "@vue/cli-plugin-vuex": {},
    "@vue/cli-plugin-eslint": {
      "config": "prettier"."lintOn": [
        "save"."commit"]}},"cssPreprocessor": "less"
}
Copy the code

The second step

Prompts. Js We can just export an empty array without providing a question; Call extendPackage methods in generator.js to add commands and packages for development and production environments to package.json; Call the Render method to copy the template

// prompts.js
module.exports = []
Copy the code
// generator.js
module.exports = (api, options, rootOptions) = > {
  api.extendPackage({
    / / command
    scripts: {
      "serve": "vue-cli-service serve"."build": "vue-cli-service build"."lint": "vue-cli-service lint"
    },
    dependencies: {
      "core-js": "^ 3.6.4 radar echoes captured." "."terser-webpack-plugin": "^ 2.3.5." "."vue": "^ 2.6.11." "."vue-router": "^ 3.1.5." "."vuex": "^ 3.1.2." "
    },
    devDependencies: {
      "@vue/cli-plugin-babel": "~ 4.2.0"."@vue/cli-plugin-eslint": "~ 4.2.0"."@vue/cli-plugin-router": "~ 4.2.0"."@vue/cli-plugin-vuex": "~ 4.2.0"."@vue/cli-service": "~ 4.2.0"."@vue/eslint-config-prettier": "^ 6.0.0"."babel-eslint": "^ 10.0.3"."eslint": "^ 6.7.2." "."eslint-plugin-prettier": "^ 3.1.1." "."eslint-plugin-vue": "^ 6.1.2." "."less": "^ 3.0.4"."less-loader": "^ 5.0.0"."lint-staged": "^ 9.5.0"."prettier": "^ 1.19.1"."vue-template-compiler": "^ 2.6.11." "}});// Copy the template
  api.render('.. /template');
};

Copy the code

The third step

Copy your project template to template and delete the package.json file. Js == _eslintrc.js, and then upload your project to gitHub

The fourth step

Use vue create –preset username/repo my-project to create your project, username/repo is your github username and preset name

complete

Here is a simple VUe-CLI project template is completed, here is a sub-template I do for iframe architecture micro front-end combat, sub-template address: github.com/luokaibin/i…

Run the vue create –preset luokaibin/iframe-child-template your-project-name command

Matters needing attention

  • Files starting with a. In the template need to be changed to _ otherwise, when creating projects using the template,. Initial file cannot be copied in; The official instructions

  • If an error occurs when creating a project using a template and you are sure it is not your own code, remove the presets from.vuerc.

  • If there are too many files of the vue-CLI default template in the project, you can delete the default template using the following method and then copy the custom template

    // generator.js
    module.exports = (api, options, rootOptions) = > {
      // Delete the vue-cli3 default directory
      api.render(files= > {
        Object.keys(files)
          .filter(path= > path.startsWith('src/') || path.startsWith('public/'))
          .forEach(path= > delete files[path])
        console.log(Object.keys(files))
      })
      api.render('.. /template');
    };
    
    Copy the code

Expand the knowledge

Inquirer

If you want to ask the user a question when creating a project using a template, such as whether to use iView or Element-UI, you must provide prompts. Js, an array that conforms to the Inquirer data structure, So you need to check out the official Inquirer documentation

Here is an example

module.exports = [
  {
    name: 'ui'.// After the question is answered, the answer is stored in that field, which is the name of the variable you want to use, key
    type: 'list'.// Question type single multiple input...
    message: 'Please select the UI library'.// Problem content shows the problem to the user
    choices: [
      {
        name: 'Element UI'.// User view options
        value: 'element-ui' // The value of this option
      },
      {
        name: 'iView'.value: 'iview'
      },
      {
        name: 'none'.value: 'none'}].default: 'none' / / the default value}]Copy the code

ejs

You will also want to render different templates depending on the UI library the user chooses, the components that are introduced, and the content. Then you will need to use ejS, the official documentation. Here is an EXAMPLE of EJS, in the Template template

<template> <%_ if (options.ui === 'element-ui') { _%> <el-container> <el-header>Header</el-header> <el-container> <el-aside width="200px">Aside</el-aside> <el-container> <el-main>Main</el-main> <el-footer>Footer</el-footer> </el-container> </el-container> </el-container> <%_ } _%> <%_ if (options.ui === 'iview') { _%> <Layout class="home"> <Header>Header</Header> <Layout class="content"> <Sider hide-trigger>Sider</Sider> <Layout> <Content>Content</Content> < Footer > Footer < Footer > < / Layout > < / Layout > < / Layout > _ < %} _ % > _ < % if (options. The UI = = = 'none') {_ % > < h1 > home page < / h1 > < % _} _%> </template> <script> export default { name: 'Home', }; </script> <style lang="stylus" scoped> <%_ if (options.ui === 'element-ui') { _%> .el-container:first-child height 100vh  .el-header, .el-footer background-color #B3C0D1 color #333 text-align center line-height 60px .el-aside background-color #D3DCE6 color #333 text-align center line-height 200px .el-main background-color #E9EEF3 color #333 text-align center line-height 160px <%_ } _%> <%_ if (options.ui === 'iview') { _%> .home height 100vh color #ffffff .content flex-direction row .ivu-layout-header background-color #2d8cf0 .ivu-layout-footer background-color #808695 color #ffffff  <%_ } _%> </style>Copy the code

Using EJS in templates can be seen in my project, which uses Inquirer and EJS, project address: github.com/luokaibin/v…

If you want to learn more about custom templates, one will need to read the official documentation, and the other will recommend a big guy’s project address: github.com/cklwblove/v… The project document is more detailed, and it also describes some pits the author stepped in the process of customizing the template. I also refer to this project for making the template, so I recommend it

series

Iframe architecture micro front-end combat

Nginx common configuration

Structural design of large front-end projects

Git management scheme for large front-end projects

How to significantly improve front-end loading performance

Installing nginx on Linux

How to implement a message prompt component (Vue) using JS calls

How to write a universal throttling and anti – shake function