【发布时间】:2022-01-13 19:46:14
【问题描述】:
我想使用 Webpack 5 将 html/index.pug 构建成 dist/index.html。
在 Webpack 4 中,我曾经为此使用 file-loader,但它在 Webpack 5 中似乎已被弃用:Loaders 页面中没有提及它。 Webpack 5 解决方案似乎正在使用 Asset Modules:该页面清楚地表明 file-loader 是 Webpack 4 的旧解决方案。
到目前为止,我还没有让它工作。这些是我在webpack.config.js 的module.rules 中尝试的几个配置:
1。仅使用pug-loader
{
test:path.resolve('./html/index.pug'),
type:'asset/resource',
loader:'pug-loader',
generator:{filename:'index.html'}}
}
这将创建一个 dist/index.html 文件,其中包含以下内容:
var pug = require("!../node_modules/pug-runtime/index.js");
function template(locals) {var pug_html = "", pug_mixins = {}, pug_interp;pug_html = pug_html + "\u003C!DOCTYPE html\u003E\u003Chtml lang=\"en\"\u003E\u003Chead\u003E\u003Ctitle\u003E" + (pug.escape(null == (pug_interp = "Hello World") ? "" : pug_interp)) + "\u003C\u002Ftitle\u003E\u003C\u002Fhead\u003E\u003Cbody\u003E\u003Cp\u003EHello World\u003C\u002Fp\u003E\u003C\u002Fbody\u003E\u003C\u002Fhtml\u003E";;return pug_html;};
module.exports = template;
看起来pug-loader 将 pug 文件转换为 JavaScript 模块,该模块在调用时生成 html 代码。我想要的是生成的 HTML 代码,而不是生成它的 JS 函数。
2。使用val-loader执行上面生成的JavaScript模块
{
test:path.resolve('./html/index.pug'),
type:'asset/resource',
use:['val-loader','pug-loader'],
generator:{filename:'index.html'}}
}
这也不起作用:Webpack 在尝试构建 dist/index.pug 时抛出错误:
ERROR in ./html/index.pug
Module build failed (from ./node_modules/val-loader/dist/cjs.js):
Error: Unable to execute "/home/bluenebula/work/webpack5-test/html/index.pug": Error: Cannot find module '!../node_modules/pug-runtime/index.js'
请注意,/home/bluenebula/work/webpack5-test/node_modules/pug-runtime/index.js 确实存在。
问题
-
资产模块是使用 Webpack 5 从 Pug 生成 HTML 文件的正确工具吗?
-
我还能做什么?
-
如何让它工作?
【问题讨论】:
-
@DimaParzhitsky 不,这些答案适用于 Webpack 4 并使用
file-loader、html-loader等。这些加载器在 Webpack 4 中使用,但 Webpack 5 引入了一个新的解决方案(资产模块),它是我正在尝试使用的东西,失败了:webpack.js.org/guides/asset-modules
标签: javascript webpack pug webpack-5 pug-loader