preface

This paper systematically summarizes the common usages of VUe-CLI3 project construction, aiming at allowing you to quickly master the ability of independent vUE project construction. You will know the following:

  • How do I install project plug-ins
  • Add browser support
  • How do I configure SCSS /stylus to share global variables
  • How to integrate third-party frameworks such as elementUI and implement on-demand introduction
  • Configure single/multiple pages
  • How do I configure custom environment variables
  • How to customize your WebPack in vue.config.js
  • Vue project deployment

instructions

At the end of this article, a configuration file for all of the above mentioned features is provided for your reference.

Mind mapping

1. Install project plug-ins

vue add @vue/cli-plugin-eslint
# or
vue add xjFile
Copy the code

Vue Add is designed to install and invoke the Vue CLI plug-in. For normal NPM packages, we can still use the package manager (depending on the selected NPM package). Finally, you can do webPack custom configuration in vue.config.js

2. Add browser support

  1. browserslist

Json file or a separate.browserslistrc file to specify the scope of the project’s target browser. This value is used by @babel/preset-env and Autoprefixer to determine which JavaScript features need to be translated and which CSS browser prefixes need to be added

Such as:

// .browserslistrc
> 1%
last 2 versions
Copy the code

To get more Browserslist, go to Browserslist

  1. Polyfill

By default, the CLI passes useBuiltIns: ‘usage’ to @babel/preset-env so that it automatically detects the required polyfill based on the language features that appear in the source code. This ensures that the number of polyfills in the final bag is minimized. But if one of these dependencies requires a special polyfill, Babel cannot detect it by default. We can solve these problems in three ways:

  • Add the dependency to the transpileDependencies option in vue.config.js
// vue.config.js
module.exports = {
    // By default babel-Loader ignores all files in node_modules. If you want to explicitly translate a dependency through Babel, you can list it in this option
    transpileDependencies: ['glob']}Copy the code
  • The required polyfill can be pre-included using the polyFills option of @vue/babel-preset-app
// babel.config.js
module.exports = {
  presets: [['@vue/app', {
      polyfills: [
        'es6.promise'.'es6.symbol']}}]]Copy the code
  • The problem with using useBuiltIns: ‘entry’ and adding import ‘@babel/polyfill’ to the entry file is that it increases the size of the package

3. Configure the SCSS /stylus shared global variable

For SCSS, you can enable it in the following ways:

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      sass: {
        // Suppose you have the 'SRC /variables. SCSS' file
        data: `@import "~@/variables.scss"; `}}}}Copy the code

For stylus, you can use the following method to test stylus:

vue add style-resources-loader

// vue.config.js
const path = require('path')
module.exports = {
  pluginOptions: {
    'style-resources-loader': {
      'patterns': [
        path.resolve(__dirname, 'src/styles/abstracts/*.styl'),]}}}Copy the code

4. Integrate third-party frameworks such as elementUI and implement on-demand introduction

  1. Install Babel – plugin – component
npm install babel-plugin-component -D
Copy the code
  1. Configure the Babel. Config. Js
module.exports = {
  presets: [
    '@vue/app',].plugins: [["component",
      {
        "libraryName": "element-ui"."styleLibraryName": "theme-chalk"}}]]Copy the code

At this point, the element component can be introduced as needed to optimize the project size.

5. Configure single/multiple pages

Vue – CLI default single page structure, we can use the configuration file to configure the project to multiple pages:

// vue.config.js
const path = require('path') module.exports = {// exports: {index: {// page'src/home/main.js', // source template:'public/index.html', // output filename in dist/index.html:'index.html', / / when using title option, / / title of the template tag needs to be < title > < % = htmlWebpackPlugin. Options. The title % > < / title > title:'Your Web For PC'By default, the blocks contained in the page will contain the generic chunk and vendor Chunk extracted from the page. // chunks: ['chunk-vendors'.'chunk-common'.'index'}, // When using an input-only string format, the // template is deduced as' public/subpage. HTML '// and falls back to' public/index.html 'if not found. // The output file name is deduced as' subpage. HTML '. // subpage:'src/subpage/main.js'}},Copy the code

6. How do I configure user-defined environment variables

You can specify environment variables by replacing the following files in your project root directory:

Env.[mode] # load only in the specified mode. Env.[mode].local # load only in the specified mode. But it is ignored by GitCopy the code

As follows:

// .env.local
APPID=123
VUE_APP_SECRET=secret
Copy the code

If you want to use environment variables in client-side code, since the variable name starts with VUE_APP_, you can get the environment variable defined as follows:

console.log(process.env.VUE_APP_SECRET)
Copy the code

How to customize webPack in vue.config.js

We can use chained calls supported by the CLI, or custom calls:

// vue- CLI internal Webpack configuration
    chainWebpack: config= > {
        // Set the shortcut directory alias
        config.resolve.alias.set('utils',resolve('.. /utils'))

        // Change the static resource packaging mode. In the following example, if the value exceeds 10K, use the file importing mode. Otherwise, use base64. The default is 4 k
        // config.module
        // .rule('images')
        // .use('url-loader')
        // .loader('url-loader')
        // .tap(options => Object.assign(options, { limit: 10240 }))
    },
    // WebPack custom configuration
    configureWebpack: config= > {
        if (process.env.NODE_ENV === 'production') {
          // Modify the configuration for the production environment...
        } else {
          // Modify the configuration for the development environment...}}Copy the code

7. Vue project deployment

In this case, we use shell scripts, but you can also use the familiar way of deployment:

#! /usr/bin/env sh
Abort the script when an error occurs
set -e

# building
npm run build

# CD to build output directory
cd dist

git init
git add -A
git commit -m 'deploy'

git push -f [email protected]:<USERNAME>/<USERNAME>.bitbucket.io.git master

cd -
Copy the code

Finally, here’s a relatively complete configuration list:

// vue.config.js
// Customize vue configuration
const path = require('path');
const resolve = dir= > path.join(__dirname, dir);
/ / the mock data
const mockData = require('./mock/test.json');

module.exports = {
    // Base path
    publicPath: '/'.// Output file directory
    // outputDir: 'dist',

    // eslint-Loader checks whether to save
    // lintOnSave: true,

    // Single/multiple pages
    pages: {
        index: {
          // Page entry
          entry: 'src/main.js'.// Source of template
          template: 'public/index.html'.// Output in dist/index.html
          filename: 'index.html'.// When using the title option,
          / / title of the template tag needs to be < title > < % = htmlWebpackPlugin. Options. The title % > < / title >
          title: 'OpenCoder For PC'.// The blocks contained in this page are included by default
          // The extracted generic chunk and Vendor chunk.
        // chunks: ['chunk-vendors', 'chunk-common', 'index']
        },
        // When using an input-only string format,
        // The template is derived as' public/subpage.html '
        // and if it cannot be found, it will fall back to 'public/index.html'.
        // The output file name is deduced as' subpage. HTML '.
        // subpage: 'src/subpage/main.js'
    },

    // CSS configuration
    css: {
        // Whether to use the CSS separation plugin ExtractTextPlugin
        extract: true.// Open CSS source maps?
        sourceMap: false.// CSS preset configuration items
        loaderOptions: {
            // stylus: {
            // // @/ is an alias for SRC /
            // // So it's assumed that you have the file 'SRC /variables. Stylus', but it's not working so far
            // data: `@import "~@/style/variables.styl"; `
            / /}
        },
        // Enable CSS modules for all CSS/pre-processor Files.
        modules: false
   },


    pluginOptions: {
        // Share variables
        'style-resources-loader': {
            preProcessor: 'stylus'.patterns: [
                // This is plus its own path,
                // Note: try not to use alias path
                resolve('src/style/variables.styl')]}},devServer: {
        / / port
        port: 3000.// Configure the proxy
        proxy: {
            '^/api': {
              target: 'http://localhost:8081'.ws: true.changeOrigin: true
            },
            '^/data': {
              target: 'http://localhost:3000'}},// mock
        before(app){
            app.get('/api/getUser',(req,res,next)=>{ res.json(mockData); })}},// vue- CLI internal Webpack configuration
    chainWebpack: config= > {
        // Set the shortcut directory alias
        config.resolve.alias.set('utils',resolve('.. /utils'))

        // Change the static resource packaging mode. In the following example, if the value exceeds 10K, use the file importing mode. Otherwise, use base64. The default is 4 k
        // config.module
        // .rule('images')
        // .use('url-loader')
        // .loader('url-loader')
        // .tap(options => Object.assign(options, { limit: 10240 }))
    },
    / / webpack configuration
    configureWebpack: config= > {
        if (process.env.NODE_ENV === 'production') {
          // Modify the configuration for the production environment...
        } else {
          // Modify the configuration for the development environment...}}}// babel.config.js
module.exports = {
  presets: [
    '@vue/app',].plugins: [["component",
      {
        "libraryName": "element-ui"."styleLibraryName": "theme-chalk"}}]]// .browserslistrc
> 1%
last 2 versions

// package.json
{
  "name": "pc"."version": "0.1.0 from"."private": true."scripts": {
    "serve": "vue-cli-service serve"."build": "vue-cli-service build"."build:serve": "serve -s dist"."lint": "vue-cli-service lint"."test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
    "clipboard": "^ 2.0.4"."core-js": "^ 2.6.5." "."element-ui": "^ 2.9.1." "."register-service-worker": "^ 1.6.2"."serve": "^ 11.0.2"."vue": "^ 2.6.10"."vue-router": "^ 3.0.3." "."vuex": "^ 3.0.1." "
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^ 3.8.0." "."@vue/cli-plugin-eslint": "^ 3.8.0." "."@vue/cli-plugin-pwa": "^ 3.8.0." "."@vue/cli-plugin-unit-mocha": "^ 3.8.0." "."@vue/cli-service": "^ 3.8.0." "."@vue/test-utils": "29 1.0.0 - beta."."babel-eslint": "^ 10.0.1." "."babel-plugin-component": "^ 1.1.1"."chai": "^ 4.1.2." "."eslint": "^ 5.16.0"."eslint-plugin-vue": "^ 5.0.0"."style-resources-loader": "^ 1.2.1." "."stylus": "^ 0.54.5"."stylus-loader": "^ 3.0.2." "."vue-cli-plugin-style-resources-loader": "^ 0.1.3"."vue-template-compiler": "^ 2.6.10"}}Copy the code

This article combs out a basic cli3 project configuration process. We can build our own projects according to this mind map.

For this article, see vue-CLI official website

If you want to obtain the mind Map HD source file, please scan the public number below:

More recommended

  • How to use gulP4 development project scaffolding

  • How to write your own JS framework in less than 200 lines of code

  • A summary of common JS functions that make you more productive in an instant

  • Developing travel List with Angular8 and Baidu Maps API

  • Js basic search algorithm implementation and 1.7 million data under the performance test

  • How to make front-end code 60 times faster

  • Front End Algorithm series array deweighting

  • How to control CSS sense of direction

  • Vue Advanced Advanced series – Play with Vue and vuex in typescript

  • In the first three years, talk about the top five books worth reading