问题描述
您会在互联网上找到很多关于设置“vanilla”webpack 配置以满足您的需求的资源。但是,我很难适应那些“普通”的 webpack 解决方案以与 webpack-encore 一起使用!
这是一个带有 configuring webpack to generate HTML assets out of TWIG/JSON source files 的示例。
到目前为止,我设法通过使用 webpack-encore's .addLoader() and .addPlugin() built-in methods 使其工作。但是有一个很大的警告:我的改编几乎是静态的,因为我必须为每个想要呈现为 HTML 的 TWIG 页面手动声明一个新插件:
Encore
[...]
.addLoader({
test: /\.twig$/,type: 'asset/source',loader: 'twig-html-loader'
})
.addPlugin(new HtmlWebpackPlugin({
title: 'Index',filename: '../html/index.html',template: './assets/twig/index.twig',publicPath: '../build/'
}))
.addPlugin(new HtmlWebpackPlugin({
title: 'Bio',filename: '../html/pages/bio.html',template: './assets/twig/bio.twig',publicPath: '../../build/'
}))
;
"vanilla" webpack 配置的示例要好得多,因为作者 wrote and made use of two custom functions 递归读取主树枝目录并列出所有文件夹中的模板,保持路径完整并排除所有模板文件.
这是我第一次使用 webpack/webpack-encore,我完全不知道如何在 webpack-encore 中使用那些原生的 javascript“walk”和“htmlPlugins”功能。
任何帮助,甚至是引导我使用新的 Google 搜索路径的关键字,都将不胜感激。谢谢!
解决方法
好的,我自己想出来了。
// create a list of twig files to generate
// filter out anything that starts with an underscore or is not a twig file
function walk(dir) {
let results = [];
const list = fs.readdirSync(dir);
list.forEach(file => {
file = `${dir}/${file}`;
const stat = fs.statSync(file);
if (stat && stat.isDirectory() && path.basename(file).indexOf('_') !== 0) {
/* Recurse into a subdirectory */
results = results.concat(walk(file));
} else if (
stat &&
!stat.isDirectory() &&
path.extname(file) === '.twig' &&
path.basename(file).indexOf('_') !== 0
) {
/* Is a file */
results.push(file);
}
});
return results;
}
//start looking in the main twig folder
const files = walk('./assets/twig');
// generate html plugins to export
const htmlPlugins = files.map(
file =>
// Create new HTMLWebpackPlugin with options
Encore.addPlugin(new HtmlWebpackPlugin({
filename: '../html/' + file.replace('./assets/twig/','').replace('.twig','.html'),template: path.resolve(__dirname,file),publicPath: '../build/',hash: true,}))
);