webpack4 多页面打包
程序员文章站
2022-05-30 21:10:30
...
方式一:
将entry修改为对象形式的多入口方式,每个入口对应对应一个html-webpack-plugin
通过html-webpack-plugin中的chunks属性,引入entry中对应的chunk
方式二:
在方法中通过glob或fs来匹配指定文件夹下的文件,遍历生成webpack对应的entry和html-webpack-plugin配置
方式一:
通过glob匹配目录后通过正则得到文件夹名称
方式二:
通过fs模块来获取文件信息
const files = fs.readdirSync('./src') 获取路径下的所有文件名
files.forEach(function (item, index) {
let stat = fs.lstatSync("./src/" + item) 获取路径中的文件信息
if (stat.isDirectory() === true) {
是文件夹的情况
}
})
通过path.dirname解析绝对路径获取到的文件夹名称会包含绝对路径的信息,所以使用fs
代码示例:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HTMLInlineCSSWebpackPlugin = require ( "html-inline-css-webpack-plugin" ). default ;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const glob = require('glob');
const fs = require('fs');
//多页面配置entry和htmlWebpackPlugin
const setOptions = ()=>{
const entry = {};
const htmlWebpackPlugin = [];
const entryFiles = glob.sync(path.resolve(__dirname, './src/*/index.js'))
const fileReg = /src\/(.*)\/index\.js/;
entryFiles.forEach((filePath, index) => {
const fileName = filePath.match(fileReg);
entry[fileName[1]] = filePath;
htmlWebpackPlugin.push(
new HtmlWebpackPlugin({
template: `./src/${fileName[1]}/index.html`,
filename:fileName[1]+'.html',
chunks:[fileName[1]]
})
)
})
return {
entry,
htmlWebpackPlugin
}
}
module.exports = {
// entry: './src/index.js',
entry: setOptions().entry,
output: {
path: path.resolve(__dirname, 'dist'),
filename:'[name]_[chunkhash:8].js'
},
module: {
rules: [
{
test: /\.js$/,
use:['babel-loader']
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"autoprefixer",
{
overrideBrowserslist: [
"Android 4.1",
"iOS 7.1",
"Chrome > 31",
"ff > 31",
"ie >= 8",
"> 1%", // 必须大于 1% 用户使用的浏览器
//'last 2 versions', // 所有主流浏览器最近的 2个版本
],
},
],
],
},
},
},
{
loader: 'px2rem-loader',
options: {
remUnit: 75, //初始稿的10分之一,代表设计稿为750,1rem=75px,
remPrecision:8, //精确的小数点位数
}
}
]
},
{
test: /\.txt$/i,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
],
}
]
},
mode: "development",
plugins: [
...setOptions().htmlWebpackPlugin,
new MiniCssExtractPlugin({filename:'css/build.css'}),
new HTMLInlineCSSWebpackPlugin(),
new CleanWebpackPlugin()
]
}