Vuejs学习笔记(三)-8.webpack中webpack.config.js中生产环境,开发环境配置文件分离
需求:目前webpack.config.js文件中即有开发环境的配置信息,又有测试环境的配置信息,比如:丑化插件希望生产环境配置,开发环境不希望配置,使用起来不太方便。
因此需要对webpack.config.js文件进行抽离。
安装插件:npm install webpack-merge@4.1.5 --save-dev
需要合并的js需要导入该组件 const webpackMerge = require('webpack-merge'),
1.新建base.config.js,开发和生产环境都需要的配置信息
1 const path = require('path') 2 const webpack = require('webpack') 3 const HtmlWebpackPlugin = require('html-webpack-plugin') 4 5 module.exports = { 6 entry: './src/main.js', 7 output: { 8 path: path.resolve(__dirname, '../dist'), 9 filename: 'bundle.js', 10 // publicPath: 'dist/' 11 }, 12 module: { 13 rules: [ 14 { 15 test: /\.css$/i, 16 use: ['style-loader', 'css-loader'] 17 }, 18 { 19 test: /\.less$/i, 20 loader: [ 21 "style-loader", 22 "css-loader", 23 "less-loader" 24 ] 25 }, 26 { 27 test: /\.(png|jpg|jpeg|gif)$/i, 28 use: [ 29 { 30 loader: 'url-loader', 31 options: { 32 //加载图片小于limit时,会将图片编辑成base64字符串形式 33 // 加载图片大于limit时,需要使用file-loader模块进行加载 34 limit: 81920, 35 name: 'img/[name].[hash:8].[ext]' 36 } 37 } 38 ] 39 }, 40 { 41 test: /\.js$/i, 42 exclude: /(node_modules|bower_components)/, 43 use: { 44 loader: 'babel-loader', 45 options: { 46 presets: ['es2015'] 47 } 48 } 49 }, 50 { 51 test:/\.vue$/i, 52 use:['vue-loader'] 53 } 54 ] 55 }, 56 resolve:{ 57 alias:{ 58 'vue$':'vue/dist/vue.esm.js' 59 }, 60 extensions:['.js','.css','.less','.vue'] 61 }, 62 plugins:[ 63 new webpack.BannerPlugin('最终版权归invoker所有'), 64 new HtmlWebpackPlugin({ 65 template:'index.html' 66 } 67 ), 68 ], 69 }
2.新建prod.config.js
1 const uglifyJsPlugin = require('uglifyjs-webpack-plugin') 2 const webpackMerge = require('webpack-merge') 3 const baseConfig = require('./base.config.js') 4 module.exports = webpackMerge(baseConfig, { 5 plugins: [ 6 new uglifyJsPlugin() 7 ] 8 })
3.新建dev.config.js
1 const webpackMerge = require('webpack-merge') 2 const baseConfig = require('./base.config.js') 3 module.exports = webpackMerge(baseConfig, { 4 devServer: { 5 // contentBase当前服务的文件夹 6 contentBase: './dist', 7 // inline表示是否需要实时监听 8 inline: true, 9 // 当前端口,默认是8080 10 // port:8080 11 } 12 })
4.webpack.config.js文件删除
5.package.json文件需要重新配置
6.执行开发环境:npm run dev
7.执行生产环境: npm run build
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/14974440.html