繁体   English   中英

将自定义 vanilla javascript 函数添加到 webpack-encore 工作流配置

[英]Add custom vanilla javascript functions to webpack-encore workflow configuration

您会在互联网上找到很多关于设置“香草”webpack 配置以满足您的需求的资源。 但是,我很难将那些“香草”webpack 解决方案与 webpack-encore 一起使用!

这是一个配置 webpack 以从 TWIG/JSON 源文件中生成 HTML 资产的示例。

到目前为止,我设法通过使用webpack-encore 的 .addLoader() 和 .addPlugin() 内置方法使其工作。 但是有一个很大的警告:我的适应几乎是 static,因为我必须为每个 TWIG 页面手动声明一个新插件,我想呈现为 HTML:

 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 配置的示例比作者编写的要好得多,并使用了两个自定义函数递归读取 twig 主目录并列出所有文件夹中的模板,保持路径完整并排除所有模板文件.

然后,他将他的自定义“htmlPlugins”立即调用 function 传递给整个 module.exports = { module.plugins } webpack 配置树作为 .concat() 方法的参数

这是我第一次使用 webpack/webpack-encore,我完全不知道如何在 webpack-encore 中使用那些普通的 javascript “walk” 和 “htmlPlugins” function。

任何帮助,甚至是引导我进入新的 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, })) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM