配置分离
安装
npm install webpack-merge@4.1.5
分离
在项目下创建build文件夹,建立3个js文件,对应base、dev和prod。
删除原来的web.config.js
base.config.js const path=require('path'); const webpack=require('webpack'); const HtmlWebpackPlugin=require('html-webpack-plugin'); module.exports= { entry: './src/main.js', output: { //绝对路径 path:path.resolve(__dirname,'dist'), filename:'bundle.js', //图片打包到这里了,所以需要更改路径 使用HTML打包后不需要这个了 // publicPath:'dist/' }, module:{ rules:[ { //正则表达式 test: /\.css$/, //css-loader只负责将css文件进行加载 //style-loader负责将样式添加到DOM中 //使用多个loader中,是从右向左的 use:['style-loader','css-loader'] }, { test:/\.(png|jpg|jpeg|gif)$/, use:[ { loader:'url-loader', options:{ //当加载的图片,小于limit时,会将图片编译成base64字符串格式 //大于limit时,需要使用file-loader 只需要安装 不用配置 limit:81920, //图片命名 name:'img/[name].[hash:8].[ext]' } } ] }, { test:/\.js$/, //exclude 排除 //include 包含 exclude:/(node_modules|bower_components)/, use:{ loader:'babel-loader', options:{ presets:['es2015'] } } }, { test:/\.vue$/, use:['vue-loader'] } ] }, resolve:{ //alias:别名 //省略后缀名 extensions:['.js','.css','.vue'], alias:{ 'vue$':'vue/dist/vue.esm.js' } }, plugins:[ new webpack.BannerPlugin('最终版权归我所有'), new HtmlWebpackPlugin({ template:'index.html' }), ], };
dev.config.js const baseConfig=require('./base.config'); const webpackMerge=require('webpack-merge'); module.exports=webpackMerge(baseConfig,{ devServer:{ contentBase:'./dist', //是否实时监听 inline:true, // port } });
prod.config.js const UglifyjsWebpackPlugin=require('uglifyjs-webpack-plugin'); const webpackMerge=require('webpack-merge'); const baseConfig=require('./base.config'); module.exports=webpackMerge(baseConfig,{ plugins:[ //开发阶段不用 打包才要 用抽离 new UglifyjsWebpackPlugin() ], });
配置
在package.json下中的
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config ./build/prod.config.js", "dev": "webpack-dev-server --open --config ./build/dev.config.js" },
执行
npm run build
注意此时打包的dist文件在build文件夹下,而不在项目文件下。
这不是我们需要的,所以此时需要更改base.config.js中的path:
path:path.resolve(__dirname,'../dist'),
开发时,执行:
npm run dev