安装webpack-merge
用于对文件进行合并,我们将开发版或产品版,让其与共用的base.config.js
进行合并
## base.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| const path = require('path');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = { mode: 'development', entry: './src/index.js', output: { path: path.resolve(__dirname, '../dist'), filename: 'bundle.js', }, module: { rules: [{ test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, { test: /\.(png|jpg|gif|jpeg)$/, use: [{ loader: 'url-loader', options: { limit: 25 * 1024, name: './img/[name].[hash:8].[ext]', },
}] }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['es2015'], } }
}, { test: /\.vue$/, use: { loader: 'vue-loader' } } ] }, plugins: [ new VueLoaderPlugin(), new webpack.BannerPlugin('最终版权归Simplelife所有'), new HtmlWebpackPlugin({ template: 'index.html' }), ], resolve: { extensions: ['.js', '.css', '.vue'], alias: { 'vue$': 'vue/dist/vue.esm.js' } },
};
|
prod.config.js
1 2 3 4 5 6 7 8 9 10
| const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const baseConfig = require('./base.config') const webpackMerge = require('webpack-merge') module.exports = webpackMerge.merge(baseConfig, { plugins: [ new UglifyJsPlugin() ] })
|
dev.config.js
1 2 3 4 5 6 7 8
| const webpackMerge = require('webpack-merge') const baseConfig = require('./base.config') module.exports = webpackMerge.merge(baseConfig, { devServer: { contentBase: './dist', inline: true } })
|
package.json
1 2 3 4 5
| "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" },
|
原先是使用webpack.config.js
,现在我们打包使用prod.config.js
,本地开发使用dev.config.js
,
后续
打包文件会自动生成在build/dist
文件夹下,因为dist
文件是基于配置文件生成的
我们自己创建的index.html
文件是不需要绑定js文件的,当我们打包后,webpack会自动帮我们绑定打包的js文件
自动生成的index.html
如下