簡體   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