Introduction to the

Vue – CLI is a Webpack-based Vue scaffolding, through vUE – CLI configuration of a set of environment can be faster development, thus improving work efficiency. While we can learn some of its configurations to become familiar with the WebPack build process for better development, this article describes how to configure a small VUe-CLI scaffolding.

Project address: Mini-vue-CLI

Basic configuration of webPack development environment

Project initialization

Refer to the Webpack documentation

NPM init NPM install webpack --save-dev NPM install --save-dev webpack-dev-server // Development environment Webpack server NPM install NPM install html-webpack-plugin --save-dev // The output file is automatically written to HTMLCopy the code

Webpack 4+ or later requires webpack-CLI

npm install --save-dev webpack-cli
Copy the code
File directory structure

webpack.common.js

const path = require("path");
module.exports = {
    entry: './src/main.js',
    output: {
        filename: 'js/main.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins:[
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true]}}),Copy the code

webpack.dev.js

const merge = require("webpack-merge"); const webpack = require("webpack"); const common = require('./webpack.common.js'); module.exports = merge(common, { devtool: 'the inline - being - the module - the source - the map', / / details https://www.webpackjs.com/configuration/devtool/ devServer: {contentBase: 'index.html', hot: true, port: 8081 }, plugins: [/ / enable hot update configuration items new webpack. NamedModulesPlugin (), new webpack. HotModuleReplacementPlugin (), new webpack.NoEmitOnErrorsPlugin(), ] })Copy the code

webpack.prod.js

const merge = require("webpack-merge");
const common = require('./webpack.common.js');
module.exports = merge(common, {
})
Copy the code

package.json

{" name ":" mini - vue - cli ", "version" : "1.0.0", "description" : "mini - vue - cli", "scripts" : {" dev ": "set NODE_ENV=development&&webpack-dev-server --inline --progress --config build/webpack.dev.js" //set NODE_ENV=development; process.env.node_env = build; "set NODE_ENV=production&&webpack --mode=production --config build/webpack.prod.js" }, "author": "", "license": "MIT", "devDependencies" : {" webpack ":" ^ 4.39.3 ", "webpack - cli" : "^ 3.3.7", "webpack - dev - server" : "^3.8.0", "webpack-merge": "^4.2.2"}}Copy the code

At this point, the configured Webpack can use NPM run dev to start the Webpack server and NPM run Build to package the imported JS resources in the main.js file

Manage resource files plug-in -loader

Install the resource management plug-in Loader

The preceding project initialization can only compile and package JS, but cannot identify resources such as CSS and images. In this case, you need to install the Loader plug-in to manage resources.

Install csS-loader file-loader url-loader sass-loader node-sass (Sass-loader and node-sass configure the SASS environment. Url-loader is based on file-loader. Can do small picture conversion base64)

npm install --save-dev style-loader css-loader file-loader sass-loader node-sass 
Copy the code

Postcss-loader autoprefixer two plug-ins can automatically prefix styles for browser compatibility

npm install postcss-loader autoprefixer --save-dev
Copy the code

When packing, pull styles from files into a file

NPM install mini-css-extract-plugin --save-dev //webpack4+ use extract-text-webpack-pluginCopy the code

Clear the files in dist before packaging

npm install clean-webpack-plugin --save-dev
Copy the code

Copy some files that do not need to be packed, for example, static folder in vue-CLI

npm install copy-webpack-plugin --save-dev
Copy the code
Configuration file

webpack.prod.js

const merge = require("webpack-merge");
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
    plugins: [
        new CleanWebpackPlugin(),
    ],
})
Copy the code

webpack.common.js

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const devMode = process.env.NODE_ENV ! = ='production';
module.exports = {
    entry: {
        app:'./src/main.js'
    },
    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, '.. /dist')
    },
    module: {
        rules: [{
                test: /\.(sa|sc|c)ss$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: process.env.NODE_ENV === 'development',
                            reloadAll: true,}},'css-loader'.'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require("autoprefixer") ({'overrideBrowserslist': ['ie 9-11'.'last 5 version'})]}}],},]}, plugins: [new HtmlWebpackPlugin({filename:'index.html',
            template: 'index.html',
            inject: true
        }),
        new MiniCssExtractPlugin({
            filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
            chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
        }),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, '.. /static'),
            to: path.resolve(__dirname, '.. /dist/static'),
            ignore: ['*']}])]}Copy the code

Vue environment related development configuration in Webpack

Arrange to compile plug-ins for Vue
npm install vue vue-router vue-style-loader vue-template-compiler --save-dev
Copy the code
Webpack configuration

webpack.common.js

const VueLoaderPlugin = require('vue-loader/lib/plugin');
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const devMode = process.env.NODE_ENV ! = ='production';
module.exports = {
    entry: {
        app:'./src/main.js'
    },
    output: {
        filename: 'js/[name].js',
        path: path.resolve(__dirname, '.. /dist')
    },
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [{
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: process.env.NODE_ENV === 'development',
                            reloadAll: true,}},'css-loader'.'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require("autoprefixer") ({'overrideBrowserslist': ['ie 9-11'.'last 5 version'[// Compatible with IE9 to 11, all latest five versions})]}}],}, {test: /\.vue$/,
                loader: 'vue-loader',
            },
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: true
        }),
        new MiniCssExtractPlugin({
            filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
            chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
        }),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, '.. /static'),
            to: path.resolve(__dirname, '.. /dist/static'),
            ignore: ['*']}])]}Copy the code
Configure vUE related files

index.html

The index. HTML file must contain a div with the id app, otherwise Cannot find element: #app.

Entry file main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './css/style.scss'
import './view/hello.vue'
new Vue({
    router,
    render: h => h(App)
}).$mount("#app")
Copy the code

Route file router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import indexPage from '.. /view/hello.vue'
Vue.use(Router);
const router = new Router({
    routes: [{
        path: '/',
        component: indexPage,
    }]
})
export default router;
Copy the code
Start the
NPM run dev // Enter localhost:8081 in the browserCopy the code
packaging
npm run build
Copy the code

Packaging optimization

Convert to ES5 syntax
NPM I babel-core babel-loader babel-preset-es2015 --save-dev // NPM I babel-plugin-transform-runtime --save-dev NPM install --save-dev babel-polyfill NPM install --save-dev babel-preset-envCopy the code
Code module splits and adds chunkhash for packaged JS additions

Separation module reference separation for each module, reference segmentfault.com/a/119000001…

Webpack.docschina.org/plugins/com… www.cnblogs.com/wmhuang/p/8…

Segmentfault.com/a/119000001…

webpack.prod.js

const merge = require("webpack-merge");
const path = require("path");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
    output: {
        filename: 'js/[name].[chunkhash]js',
        path: path.resolve(__dirname, '.. /dist'),
    },
    optimization: {
        namedChunks: true,
        runtimeChunk: {
            name: 'manifest'
        },
        noEmitOnErrors: trueSplitChunks: {chunks:'async',
            minSize: 30000,
            minChunks: 1,
            maxAsyncRequests: 5,
            maxInitialRequests: 3,
            name: false,
            cacheGroups: {
                vendor: {
                    name: 'vendor',
                    chunks: 'initial',
                    priority: -10,
                    reuseExistingChunk: false.test: /node_modules\/(.*)\.js/
                },
            }
        }
    },
    plugins: [
        new CleanWebpackPlugin(),
    ],
})
Copy the code