webpack4打包多文件
//引包
var path = require("path"); //需要使用绝对路径
var HtmlWebpackPlugin= require("html-webpack-plugin");
const webpack=require("webpack");
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
var glob = require("glob")
//打包单文件
module.exports= {
entry:{
index:'./src/index.js'
},
output:{
path: path.join(__dirname, 'dist'),
filename: 'js/index.js'
}
...
plugins:[
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
hash: true,
minify: {
removeAttributeQuotes:true,
removeComments: true,
collapseWhitespace: true,
removeScriptTypeAttributes:true,
removeStyleLinkTypeAttributes:true
}
})
]
}
//打包多文件
webpack.config.js :
function getView(globPath,flag){
let files = glob.sync(globPath);
let entries = {},
entry, dirname, basename, pathname, extname;
files.forEach(item => {
entry = item;
dirname = path.dirname(entry);//当前目录
extname = path.extname(entry);//后缀
basename = path.basename(entry, extname);//文件名
pathname = path.join(dirname, basename);//文件路径
if (extname === '.html') {
entries[pathname] = './' + entry;
} else if (extname === '.js') {
entries[basename] = entry;
}
});
return entries;
}
//打包html
let pages = Object.keys(getView('./src/*html'));
let htmlPlugins = []
pages.forEach(pathname => {
let htmlname = pathname.split('src\\')[1];
let conf = {
filename: `${htmlname}.html`,
template: `${pathname}.html`,
hash: true,
chunks:[htmlname],
minify: {
removeAttributeQuotes:true,
removeComments: true,
collapseWhitespace: true,
removeScriptTypeAttributes:true,
removeStyleLinkTypeAttributes:true
}
}
htmlPlugins.push(new HtmlWebpackPlugin(conf));
});
module.exports= {
mode: 'production', // 这里写成线上环境,开发环境则切换成 development
entry: jsEntries,
output: {
// 静态资源文件的本机输出目录
path: path.resolve(__dirname, 'build'),
// 静态资源服务器发布目录
publicPath: '/',
// 入口文件名称配置
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js'
},
module: {
rules: [
{
test: /\.pug$/,
use: 'pug-loader'
},
{
test: /\.jsx?$/,
use: 'babel-loader?cacheDirectory',
exclude: /node_modules/
}
]
},
...
plugins:[
...htmlPlugins,
]
}
可以参考:
https://www.izhongxia.com/posts/44724.html