How to change vue.config.js to build different topics of the same project in vue3.0-vue-cli development environment

Time:2021-9-10

Thinking: different customers of the same project have different themes. How to configure them to build different themes quickly and conveniently?

1. Most people will think of extracting topics into separate CSS files (CSS precompiled language: less, stylus, SCSS) for subcontracting management, which is necessary

2. If it is multilingual, the corresponding Chinese of each customer is slightly different, and it should also be split for management

After splitting, how to add configuration to configure permanent use at one time? You can’t manually change the entry file every time you build (it’s time-consuming and laborious)~~

 

Idea: the new Vue cli development scaffold is said to be 0 configuration, but the configuration needs to be added or adapted vue.config.js, and then combined with nodejs to achieve the above optimal solution

 

For example:

1. First, we add different variable entries in the scripts section of package.json, namely_ Path defines a node environment variable at the entrance, so that after NPM run dev: Dajiang, vue.config.js can read process.env.this_ The value of path is equal to Dajiang (about node reference)http://nodejs.cn/api/), you need to install: NPM install – D cross env here

 

 

 

2. Get process.env.these in vue.config.js_ After the value of path, let’s add the configuration of webpack to vue.config.js

'use strict'
const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const themeSrc = process.env.THEME_PATH || 'default'

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  //Customize the configuration of webpack
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        //Configure the alias so that all paths to access: themepath are controlled by variables
        'themePath': resolve(`src/styles/theme/${themeSrc}`)
      }
    }
  }
}

 

3. After the above configuration is completed, the path configuration has been completed. The rest is to add the corresponding customer theme and introduce it for use, as follows: Styles / theme / default corresponds to the default theme, dev in package.json, default / index.js corresponds to the multilingual configuration of the theme, and default / index.scss for the default theme (SCSS variable)

 

 

 

 

4. It’s easy to use, because after configuration, the configured path will be read as long as the path accessing themepath is encountered, such as:

 

In this way, you will read the parameters behind NPM run dev: XX and NPM run build: XX. Reading JS is similar, and even if you import veriables.scss inside the component, you can directly use variables.