我正在尝试仅使用 Webpack 创建一个基本网站。我的目的是拥有一个简单的 URL 结构,例如 example.com/about、example.com/contact。
在 Webpack 中,我可以使用 HTMLWebpackPlugin,但是我需要为每个路由创建一个实例。所以,我的问题是:有没有办法简化这个?
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
port: 5000,
},
plugins: [
new htmlWebpackPlugin({
title: 'Home',
filename: 'index.html',
template: './src/pages/home/index.html',
}),
new htmlWebpackPlugin({
title: 'About',
filename: 'about/index.html',
template: './src/pages/about/index.html',
}),
],
};
Run Code Online (Sandbox Code Playgroud)
您的 Webpack 配置文件是 javascript。因此,您可以添加一些辅助函数来抽象该过程,并最终插入一组将产生所需效果的页面:
const htmlWebpackPlugin = require('html-webpack-plugin');
const generateHtmlPlugin = (title) => {
return new htmlWebpackPlugin({
title,
filename: 'index.html',
template: `./src/pages/${title.toLowerCase()}/index.html`,
});
}
const populateHtmlPlugins = (pagesArray) => {
res = [];
pagesArray.forEach(page => {
res.push(generateHtmlPlugin(page));
})
return res;
}
Run Code Online (Sandbox Code Playgroud)
所以这不是太多的代码,它允许你在设置 webpack 时插入一组你想要的页面:
const pages = populateHtmlPlugins(["About", "Articles", "Users", "Contact"]);
module.exports = {
//...
plugins: pages
}
Run Code Online (Sandbox Code Playgroud)
更好的是,您可以创建一个utils
文件夹并将代码重构为两个导出的模块,然后只需导入populateHtmlPlugins()
您的 webpack 配置文件并保持非常干净。
现在,您可以轻松地创建任意数量的页面。