directory
- √ Configure multiple environment variables
- √ Configure basic vue.config.js
- √ Configure proxy across domains
- √ Fix HMR(hot update) failure
- √ Fix Lazy loading routes Error: Cyclic Dependency
- √ Add an alias
- √ Remove redundant and invalid CSS
- √ Add package analysis
- Square root configuration externals
- Tick off the console. The log
- √ Enable Gzip compression
- √ Provides global styles for Sass, as well as global variables
- √ Add COMPATIBILITY with IE
- √ File upload ali OSS
- √ Full dependence
☞ Configure multiple environment variables
Select different environments by adding –mode XXX to the scripts configuration item in package.json
Create. Env,.env.production,.env.analyz and other files in the project root directory
Only variables starting with VUEAPP are statically embedded in the client-side package by webpack.defineplugin and can be accessed in the code via process.env.vue_app_base_API
NODE_ENV and BASE_URL are two special variables that are always available in the code
Env serve Default environment variable
NODE_ENV = 'development'
VUE_APP_BASE_API = 'https://demo.cn/api'
Copy the code
.env.production build The default environment variable
If open ali oss, VUE_APP_SRC configured to ali oss resource url prefix, such as: ‘staven.oss-cn-hangzhou.aliyuncs.com/demo’
NODE_ENV = 'production' VUE_APP_BASE_API = 'https://demo.com/api' VUE_APP_SRC = '/' ACCESS_KEY_ID = '' ACCESS_KEY_SECRET = '' REGION = 'oss-cn-hangzhou' BUCKET = 'staven' PREFIX = 'demo'
Copy the code
Env. analyz is used for webpack-bundle-Analyzer package analysis
If open ali oss, VUE_APP_SRC configured to ali oss resource url prefix, such as: ‘staven.oss-cn-hangzhou.aliyuncs.com/demo’
NODE_ENV = 'production' IS_ANALYZ = 'analyz' VUE_APP_BASE_API = 'https://demo.com/api' VUE_APP_SRC = '/' ACCESS_KEY_ID = '' ACCESS_KEY_SECRET = '' REGION = 'oss-cn-hangzhou' BUCKET = 'staven' PREFIX = 'demo'
Copy the code
Modify the package. The json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"analyz": "vue-cli-service build --mode analyz",
"lint": "vue-cli-service lint"
}
Copy the code
Bring back to the top
☞ Basic Configuration vue.config.js
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV); Module.exports = {baseUrl: './', // default '/', baseUrl outputDir for deploying application packages: Process. The env. OutputDir | | 'dist' / / 'dist, production environment assetsDir build file directory: // Static resources (js, CSS, img, fonts) directory relative to outputDir lintOnSave: false, runtimeCompiler: ProductionSourceMap: false, // Source map parallel for production environment: require('os').cpus().length > 1, pwa: {} };
Copy the code
☞ Configure proxy across domains
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV); module.exports = { devServer: { // overlay: { // warnings: true, // errors: true // }, open: IS_PROD, host: '0.0.0.0', port: 8000, HTTPS: false, hotOnly: false, proxy: {'/ API ': {target: Process. The env. VUE_APP_BASE_API | | 'http://127.0.0.1:8080', changeOrigin: true}}}}
Copy the code
☞ Repair HMR(hot update) failure
Module.exports = {chainWebpack: config => {// fix HMR config.resolve.symlinks(true); }}
Copy the code
☞ Fix Lazy loading routes Error: Cyclic DependencyGithub.com/vuejs/vue-c…
module.exports = { chainWebpack: config => { config.plugin('html').tap(args => { args[0].chunksSortMode = 'none'; return args; }); }}
Copy the code
Bring back to the top
☞ Add alias
const path = require('path'); const resolve = (dir) => path.join(__dirname, dir); const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV); module.exports = { chainWebpack: Config => {// add alias config.resolve.alias. set('@', resolve(' SRC ')).set('assets', resolve('src/assets')) .set('components', resolve('src/components')) .set('layout', resolve('src/layout')) .set('base', resolve('src/base')) .set('static', resolve('src/static')); }}
Copy the code
☞ Remove redundant and invalid CSS
npm i --save-dev glob-all purgecss-webpack-plugin
Copy the code
const PurgecssPlugin = require('purgecss-webpack-plugin'); const glob = require('glob-all'); const path = require('path') module.exports = { configureWebpack: config => { if (IS_PROD) { const plugins = []; plugins.push( new PurgecssPlugin({ paths: glob.sync([ path.join(__dirname, './src/index.html'), path.join(__dirname, './**/*.vue'), path.join(__dirname, './src/**/*.js') ]) }) ); config.plugins = [ ...config.plugins, ...plugins ]; }}}
Copy the code
☞ Add packaging analysis
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
chainWebpack: config => {
// 打包分析
if (process.env.IS_ANALYZ) {
config.plugin('webpack-report')
.use(BundleAnalyzerPlugin, [{
analyzerMode: 'static',
}]);
}
}
}
Copy the code
☞ configuration externals
Prevent packages from being packaged into bundles, and instead obtain these extension dependencies externally at runtime
module.exports = {
configureWebpack: config => {
config.externals = {
'vue': 'Vue',
'element-ui': 'ELEMENT',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'axios': 'axios'
}
}
}
Copy the code
☞. Remove the console log
Method one:
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { configureWebpack: config => { if (IS_PROD) { const plugins = []; plugins.push( new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false, drop_console: true, drop_debugger: False, pure_funcs: ['console.log']// Remove console}}, sourceMap: false, parallel: true}); config.plugins = [ ...config.plugins, ...plugins ]; }}}
Copy the code
Method 2: Use the babel-plugin-transform-remove-console plug-in
npm i --save-dev babel-plugin-transform-remove-console
Copy the code
Configure in babel.config.js
const plugins = [];
if(['production', 'prod'].includes(process.env.NODE_ENV)) {
plugins.push("transform-remove-console")
}
module.exports = {
presets: [["@vue/app",{"useBuiltIns": "entry"}]],
plugins: plugins
};
Copy the code
☞ Enable Gzip compression
npm i --save-dev compression-webpack-plugin
Copy the code
const CompressionWebpackPlugin = require('compression-webpack-plugin'); const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\? . *)? $/i; module.exports = { configureWebpack: config => { if (IS_PROD) { const plugins = []; plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: ProductionGzipExtensions, threshold: 10240, minRatio: 0.8})); config.plugins = [ ...config.plugins, ...plugins ]; }}}
Copy the code
You can also open Zopfli compression is better than gzip experience can be found in the webpack.js.org/plugins/com…
npm i --save-dev @gfx/zopfli brotli-webpack-plugin
Copy the code
const CompressionWebpackPlugin = require('compression-webpack-plugin'); const zopfli = require("@gfx/zopfli"); const BrotliPlugin = require("brotli-webpack-plugin"); const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\? . *)? $/i; module.exports = { configureWebpack: config => { if (IS_PROD) { const plugins = []; plugins.push( new CompressionWebpackPlugin({ algorithm(input, compressionOptions, callback) { return zopfli.gzip(input, compressionOptions, callback); }, compressionOptions: {numiterations: 15}, minRatio: 0.99, test: productionGzipExtensions}); Plugins. Push (new BrotliPlugin (0.99} {test: productionGzipExtensions minRatio:)); config.plugins = [ ...config.plugins, ...plugins ]; }}}
Copy the code
☞ Provide the global style for Sass, as well as global variables
Vue.prototype.$SRC = process.env.vue_app_src; Mount the configuration information in the environment variable and access it in js using $SRC.
The CSS can use the injected SASS variable to access configuration information in environment variables
module.exports = { css: { modules: false, extract: IS_PROD, sourceMap: false, loaderOptions: { sass: {/ / to the global sass styling to share global variable data: ` @ import "~ assets/SCSS/variables. SCSS"; $src: "${process.env.VUE_APP_SRC}"; '}}}}
Copy the code
Referenced in SCSS
.home {
background: url($src + '/images/500.png');
}
Copy the code
☞ Add IE compatibility
npm i --save @babel/polyfill
Copy the code
Add it in main.js
import '@babel/polyfill';
Copy the code
Configure the Babel. Config. Js
const plugins = [];
module.exports = {
presets: [["@vue/app",{"useBuiltIns": "entry"}]],
plugins: plugins
};
Copy the code
☞ File upload ali OSS
To enable file uploading ali OSS, change baseUrl to the prefix of ali OSS resource URL, that is, change VUE_APP_SRC
npm i --save-dev webpack-oss
Copy the code
const AliOssPlugin = require('webpack-oss'); module.exports = { configureWebpack: config => { if (IS_PROD) { const plugins = []; / / upload the file to the oss the if (process. The env. ACCESS_KEY_ID | | process. The env. ACCESS_KEY_SECRET | | process. The env. The REGION | | process. The env. The BUCKET || process.env.PREFIX) { plugins.push( new AliOssPlugin({ accessKeyId: process.env.ACCESS_KEY_ID, accessKeySecret: process.env.ACCESS_KEY_SECRET, region: process.env.REGION, bucket: process.env.BUCKET, prefix: process.env.PREFIX, exclude: /.*\.html$/, deleteAll: false }) ); } config.plugins = [ ...config.plugins, ...plugins ]; }}}
Copy the code
☞ Complete configuration
- Install dependencies
npm i --save-dev compression-webpack-plugin babel-plugin-transform-remove-console glob-all purgecss-webpack-plugin
Copy the code
Other dependencies (@gFX/Zopfli, BrotLi-webpack-plugin, webpack-OSS) can be installed as required
- Environment configuration
.env
NODE_ENV = 'development'
VUE_APP_BASE_API = 'https://demo.cn/api'
Copy the code
.env.production
If open ali oss, VUE_APP_SRC configured to ali oss resource url prefix, such as: ‘staven.oss-cn-hangzhou.aliyuncs.com/demo’
NODE_ENV = 'production' VUE_APP_BASE_API = 'https://demo.com/api' VUE_APP_SRC = '/' ACCESS_KEY_ID = '' ACCESS_KEY_SECRET = '' REGION = 'oss-cn-hangzhou' BUCKET = 'staven' PREFIX = 'demo'
Copy the code
.env.analyz
If open ali oss, VUE_APP_SRC configured to ali oss resource url prefix, such as: ‘staven.oss-cn-hangzhou.aliyuncs.com/demo’
NODE_ENV = 'production'
IS_ANALYZ = 'analyz'
VUE_APP_BASE_API = 'https://demo.com/api'
VUE_APP_SRC = VUE_APP_SRC = '/'
ACCESS_KEY_ID = ''
ACCESS_KEY_SECRET = ''
REGION = 'oss-cn-hangzhou'
BUCKET = 'staven'
PREFIX = 'demo'
Copy the code
- package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"analyz": "vue-cli-service build --mode analyz",
"lint": "vue-cli-service lint"
}
Copy the code
- babel.config.js
const plugins = [];
// if(['production', 'prod'].includes(process.env.NODE_ENV)) {
// plugins.push("transform-remove-console")
// }
module.exports = {
presets: [["@vue/app",{"useBuiltIns": "entry"}]],
plugins: plugins
};
Copy the code
- vue.config.js
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer") .BundleAnalyzerPlugin; const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const CompressionWebpackPlugin = require("compression-webpack-plugin"); // const zopfli = require("@gfx/zopfli"); // const BrotliPlugin = require("brotli-webpack-plugin"); const AliOssPlugin = require("webpack-oss"); const path = require("path"); const PurgecssPlugin = require("purgecss-webpack-plugin"); const glob = require("glob-all"); const resolve = dir => path.join(__dirname, dir); const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV); const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\? . *)? $/i; module.exports = { baseUrl: IS_PROD ? Process. The env. VUE_APP_SRC | | "/" : ". / ", / / '/' by default, the deployment of packages of the basic outputDir URL: Process. The env. OutputDir | | "dist", / / 'dist, production environment assetsDir build file directory: // Static resources (js, CSS, img, fonts) directory relative to outputDir lintOnSave: false, runtimeCompiler: ProductionSourceMap: false, // SourceMap configureWebpack for production environment: Externals = {// 'vue': 'vue', // 'element-ui': 'element ', // 'vue-router': 'VueRouter', // 'vuex': 'Vuex', // 'axios': 'axios' // } if (IS_PROD) { const plugins = []; plugins.push( new PurgecssPlugin({ paths: glob.sync([ path.join(__dirname, "./src/index.html"), path.join(__dirname, "./**/*.vue"), path.join(__dirname, "./src/**/*.js") ]) }) ); plugins.push( new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false, drop_console: true, drop_debugger: False, pure_funcs: ["console.log"] // Remove console}}, sourceMap: false, parallel: true}); plugins.push( new CompressionWebpackPlugin({ filename: "[path].gz[query]", algorithm: "gzip", test: ProductionGzipExtensions, threshold: 10240, minRatio: 0.8})); / / upload files to the oss / / if (process. The env. ACCESS_KEY_ID | | process. The env. ACCESS_KEY_SECRET | | process. The env. The REGION | | process. The env. The BUCKET || process.env.PREFIX) { // plugins.push( // new AliOssPlugin({ // accessKeyId: process.env.ACCESS_KEY_ID, // accessKeySecret: process.env.ACCESS_KEY_SECRET, // region: process.env.REGION, // bucket: process.env.BUCKET, // prefix: process.env.PREFIX, // exclude: /.*\.html$/, // deleteAll: false // }) // ); } // Zopfli compression, Need to respond to VC library/https://webpack.js.org/plugins/compression-webpack-plugin/ / plugins. Push (/ / new CompressionWebpackPlugin ({/ / algorithm(input, compressionOptions, callback) { // return zopfli.gzip(input, compressionOptions, callback); // Iterations: {// numsionoptions: 15 //}, // minRatio: 0.99, // test: productionGzipExtensions // }) // ); / / plugins. Push (/ / new BrotliPlugin ({/ / test: productionGzipExtensions, / / minRatio: 0.99 / /}) / /); config.plugins = [...config.plugins, ...plugins]; }}, chainWebpack: config => {// fix HMR config.resolve.symlinks(true); // Fix Lazy loading routes Error: Cyclic dependency [https://github.com/vuejs/vue-cli/issues/1669] config.plugin("html").tap(args => { args[0].chunksSortMode = "none"; return args; }); Set ("@", resolve(" SRC ")). Set ("assets", resolve(" SRC /assets")). Set ("components", resolve("src/components")) .set("layout", resolve("src/layout")) .set("base", resolve("src/base")) .set("static", resolve("src/static")); If (process.env.is_analyz) {config.plugin("webpack-report"). Use (BundleAnalyzerPlugin, [{analyzerMode: "static" } ]); } // Multi-page configuration, To add the hash/js/config. The output. ChunkFilename (` js / [name] [8] chunkhash: js `) / / / config/modify image output path. The rule (' images') module / /. // .test(/\.(png|jpe?g|gif|ico)(\?.*)?$/) // .use('url-loader') // .loader('url-loader') // .options({ // name: path.join('.. /assets/', 'img/[name].[ext]') //})}, CSS: {modules: false, extract: IS_PROD, // Add hash to CSS suffix {/ / filename: 'CSS / [name] [8] hash: CSS', / / chunkFilename: 'CSS / [name] [8] hash: CSS' / /}, sourceMap: False, loaderOptions: {sass: {/ / to the global sass styling to Shared global variables / / data: ` @ import "~ assets/SCSS/variables. SCSS"; $src: "${process.env.VUE_APP_SRC}"; ` data: `$src: "${process.env.VUE_APP_SRC}"; } // plugins: [// require('postcss-pxtorem')({// rootValue: 1, / / / / conversion of base selectorBlackList: [' weui ', 'el], / / ignore conversion regular match / / propList: [' *'] / / / / / /}}}}), pluginOptions: {// install vue cli-plugin-style-resources-loader plug-in // add global style global. SCSS // "style-resources-loader": {// install vue cli-plugin-style-resources-loader plug-in // add global style global. SCSS // "style-resources-loader": {// preProcessor: "scss", // patterns: [ // resolve(__dirname, "./src/scss/scss/variables.scss") // ] // } }, parallel: require("os").cpus().length > 1, pwa: {}, devServer: { // overlay: { // warnings: true, // errors: true // }, open: IS_PROD, host: "0.0.0.0", port: 8000, HTTPS: false, hotOnly: false, proxy: {"/ API ": {target: Process. The env. VUE_APP_BASE_API | | "http://127.0.0.1:8080", changeOrigin: true}}}};
Copy the code