vue-cli3全面配置详解
本文介绍了vue-cli3全面配置详解,分享给大家,具体如下:
创建项目
配置环境变量
通过在package.json里的scripts配置项中添加--mode xxx来选择不同环境
在项目根目录中新建.env, .env.production, .env.analyz等文件
只有以 vue_app_ 开头的变量会被 webpack.defineplugin 静态嵌入到客户端侧的包中,代码中可以通过process.env.vue_app_base_api访问
node_env 和 base_url 是两个特殊变量,在代码中始终可用
.env serve默认的环境变量
node_env = 'development' vue_app_base_api = 'https://demo.cn/api' vue_app_src = 'https://wechat-timg.oss-cn-hangzhou.aliyuncs.com/demo'
.env.production build默认的环境变量
node_env = 'production' vue_app_base_api = 'https://demo.com/api' vue_app_src = 'https://img-wechat.oss-cn-hangzhou.aliyuncs.com/demo'
.env.analyz 用于webpack-bundle-analyzer打包分析
node_env = 'production' is_analyz = 'analyz' vue_app_base_api = 'https://demo.com/api' vue_app_src = 'https://img-wechat.oss-cn-hangzhou.aliyuncs.com/demo'
修改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" }
配置vue.config.js
const is_prod = ['production', 'prod'].includes(process.env.node_env); module.exports = { baseurl: './', // 默认'/',部署应用包时的基本 url outputdir: process.env.outputdir || 'dist', // 'dist', 生产环境构建文件的目录 assetsdir: '', // 相对于outputdir的静态资源(js、css、img、fonts)目录 lintonsave: false, runtimecompiler: true, // 是否使用包含运行时编译器的 vue 构建版本 productionsourcemap: false, // 生产环境的 source map parallel: require('os').cpus().length > 1, pwa: {} };
配置proxy跨域
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.env.vue_app_base_api || 'http://127.0.0.1:8080', changeorigin: true } } } }
修复hmr(热更新)失效
module.exports = { chainwebpack: config => { // 修复hmr config.resolve.symlinks(true); } }
添加别名
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 => { // 添加别名 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')); } }
添加打包分析
const bundleanalyzerplugin = require('webpack-bundle-analyzer').bundleanalyzerplugin; module.exports = { chainwebpack: config => { // 打包分析 if (process.env.is_analyz) { config.plugin('webpack-report') .use(bundleanalyzerplugin, [{ analyzermode: 'static', }]); } } }
配置externals
防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖
module.exports = { configurewebpack: config => { config.externals = { 'vue': 'vue', 'element-ui': 'element', 'vue-router': 'vuerouter', 'vuex': 'vuex', 'axios': 'axios' } } }
去掉console.log
方法一:
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']//移除console } }, sourcemap: false, parallel: true }) ); config.plugins = [ ...config.plugins, ...plugins ]; } } }
方法二:使用babel-plugin-transform-remove-console插件
npm i --save-dev babel-plugin-transform-remove-console
在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 };
开启gzip压缩
npm i --save-dev compression-webpack-plugin
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 ]; } } }
还可以开启比gzip体验更好的zopfli压缩详见
npm i --save-dev @gfx/zopfli brotli-webpack-plugin
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({ test: productiongzipextensions, minratio: 0.99 }) ); config.plugins = [ ...config.plugins, ...plugins ]; } } }
为sass提供全局样式,以及全局变量
可以通过在main.js中vue.prototype.$src = process.env.vue_app_src;挂载环境变量中的配置信息,然后在js中使用$src访问。
css中可以使用注入sass变量访问环境变量中的配置信息
module.exports = { css: { modules: false, extract: is_prod, sourcemap: false, loaderoptions: { sass: { // 向全局sass样式传入共享的全局变量 data: `@import "~assets/scss/variables.scss";$src: "${process.env.vue_app_src}";` } } } }
在scss中引用
.home { background: url($src + '/images/500.png'); }
添加ie兼容
npm i --save @babel/polyfill
在main.js中添加
import '@babel/polyfill';
配置babel.config.js
const plugins = []; module.exports = { presets: [["@vue/app",{"usebuiltins": "entry"}]], plugins: plugins };
完整配置
安装依赖
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" }
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 }; 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 path = require('path'); 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: './', // 默认'/',部署应用包时的基本 url outputdir: process.env.outputdir || 'dist', // 'dist', 生产环境构建文件的目录 assetsdir: '', // 相对于outputdir的静态资源(js、css、img、fonts)目录 lintonsave: false, runtimecompiler: true, // 是否使用包含运行时编译器的 vue 构建版本 productionsourcemap: false, // 生产环境的 source map configurewebpack: config => { // config.externals = { // 'vue': 'vue', // 'element-ui': 'element', // 'vue-router': 'vuerouter', // 'vuex': 'vuex', // 'axios': 'axios' // } if (is_prod) { const plugins = []; plugins.push( new uglifyjsplugin({ uglifyoptions: { compress: { warnings: false, drop_console: true, drop_debugger: false, pure_funcs: ['console.log']//移除console } }, sourcemap: false, parallel: true }) ); plugins.push( new compressionwebpackplugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: productiongzipextensions, threshold: 10240, minratio: 0.8 }) ); // zopfli压缩 https://webpack.js.org/plugins/compression-webpack-plugin/ // 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({ // test: productiongzipextensions, // minratio: 0.99 // }) // ); config.plugins = [ ...config.plugins, ...plugins ]; } }, chainwebpack: config => { // 修复hmr config.resolve.symlinks(true); // 添加别名 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')); // 打包分析 if (process.env.is_analyz) { config.plugin('webpack-report') .use(bundleanalyzerplugin, [{ analyzermode: 'static', }]); } // 多页面配置,为js添加hash // config.output.chunkfilename(`js/[name].[chunkhash:8].js`) // 修改图片输出路径 // config.module // .rule('images') // .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, // 为css后缀添加hash // extract: { // filename: 'css/[name].[hash:8].css', // chunkfilename: 'css/[name].[hash:8].css' //}, sourcemap: false, loaderoptions: { sass: { // 向全局sass样式传入共享的全局变量 // data: `@import "~assets/scss/variables.scss";$src: "${process.env.vue_app_src}";` data: `$src: "${process.env.vue_app_src}";` }, // px转换为rem // postcss: { // plugins: [ // require('postcss-pxtorem')({ // rootvalue : 1, // 换算的基数 // selectorblacklist : ['weui', 'el'], // 忽略转换正则匹配项 // proplist : ['*'] // }) // ] // } } }, pluginoptions: { // 安装vue-cli-plugin-style-resources-loader插件 // 添加全局样式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.env.vue_app_base_api || 'http://127.0.0.1:8080', changeorigin: true } } } };
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。