Webpack 5中JSON未按asset/resource加载,pug-plugin引用Webmanifest异常求助
解决Pug模板中加载webmanifest.json时href被替换为JSON内容的问题
问题原因
webpack默认会将JSON文件解析为JavaScript对象,当你在Pug模板中使用require引入时,pug-plugin会把解析后的对象转为字符串,最终导致href被填充为JSON内容而非文件URL。
解决办法
方法1:使用加载器前缀强制处理
在require时直接指定asset/resource加载器,强制webpack将该JSON文件作为资源输出,返回文件URL:
link(rel="manifest" href=require("!asset/resource!/meta/webmanifest.json"))
方法2:调整webpack规则优先级,单独处理webmanifest.json
在webpack配置中,给webmanifest.json单独设置规则(优先级高于通用JSON规则),确保它被当作资源文件处理:
module.exports = { module: { rules: [ // 优先处理webmanifest.json { test: /webmanifest\.json$/, type: "asset/resource", // 可选:指定输出文件名格式 generator: { filename: "meta/[name][ext]" } }, // 通用资源规则(排除已处理的webmanifest) { test: /\.(ico|svg|png|ttf|json)$/, exclude: /webmanifest\.json$/, type: "asset/resource" }, // pug-loader规则 { test: /\.pug$/, use: ["@webdiscus/pug-loader"] } ] }, plugins: [ new PugPlugin({ entry: { index: "./src/index.pug" // 替换为你的Pug入口文件 } }) ] };
方法3:更新pug-plugin到最新版本
旧版本的pug-plugin可能对webpack的asset/resource类型支持存在问题,执行更新命令:
npm update @webdiscus/pug-plugin
内容的提问来源于stack exchange,提问作者elldur
相关产品推荐
相关产品推荐

