1、安装html-webpack-plugin
cnpm install --save-dev html-webpack-plugin
将原来的index.html改成index.tmpl.html,并移除里面的script标签。
webpack.config.js引入并配置
const htmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
new htmlWebpackPlugin({
filename: 'index.html',
template: 'index.tmpl.html',
minify: {
removeAttributeQuotes: true // 移除属性的引号
}
})
]
执行webpack --mode development,dits目录下就生成了编译好的index.html文件。
顺便output选项在原来基础上加上hash或chunkhash,推荐chunkhash,用来清缓存
output: {
path: __dirname + "/dist",//打包后的文件存放的地方
filename: "bundle-[chunkhash].js",//打包后输出文件的文件名
publicPath: 'dist/'
},
2、安装extract-text-webpack-plugin
cnpm install extract-text-webpack-plugin@next
因为与webpack4的兼容性问题,后面得加上@next,或者推荐使用mini-css-extract-plugin,但没有找到从vue文件剥离css的配置,暂时还使用老的插件
针对vue文件进行配置
const ExtractTextPlugin = require('extract-text-webpack-plugin');
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
css: ExtractTextPlugin.extract({
use: ['css-loader'],
fallback: 'vue-style-loader'
})
}
}
}
new ExtractTextPlugin('[name]-[chunkhash].css')
执行webpack --mode development,dits目录下就生成了剥离出来的css文件
3、使用了hash,每次编译都会生成不同的文件,为了删除多余的文件,引入clean-webpack-plugin插件
cnpm install --save-dev clean-webpack-plugin
const CleanWebpackPlugin = require("clean-webpack-plugin");
new CleanWebpackPlugin('dist/*.*', {
root: __dirname,
verbose: true,
dry: false
})
执行webpack --mode development,dits目录下之前生成的文件已删除,只保留当前版本的文件