You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决自定义Webpack Loader返回字符串时的Module parse failed错误

开发PUG AST Webpack Loader的问题

我想开发一个能加载PUG AST的Webpack Loader,初始实现代码如下:

import PugLexer from "pug-lexer";
import generatePugAST from "pug-parser";

const pugAstLoader: (source: string) => string | null = function(source: string): string | null {
  try {
    const tokens: PugLexer.Token[] = PugLexer("div test");
    const AST = generatePugAST(tokens, { filename: "Test.pug", src: source });
    return AST;
  } catch (error: unknown) {
    console.error(error);
    return null;
  }
};

export default pugAstLoader;

运行Webpack时出现报错:

ERROR in ./Components/Custom.custom.pug
Module build failed: Error: Final loader (../PugAST_Loader.ts) didn't return a Buffer or String

我清楚Loader必须返回Buffer或字符串,于是将AST转换为字符串,修改后的代码如下:

import PugLexer from "pug-lexer";
import generatePugAST from "pug-parser";

const pugAstLoader: (source: string) => string | null = function(source: string): string | null {
  try {
    const tokens: PugLexer.Token[] = PugLexer("div test");
    const AST = generatePugAST(tokens, { filename: "Test.pug", src: source });
    return JSON.stringify(AST);
  } catch (error: unknown) {
    console.error(error);
    return null;
  }
};

export default pugAstLoader;

现在又出现新的错误:

ERROR in ./Components/Custom.custom.pug 1:7
Module parse failed: Unexpected token (1:7)
File was processed with these loaders:
 * ../PugAST_Loader.ts
You may need an additional loader to handle the result of these loaders.
> {"type":"Block",// ...
 @ ./index.ts 8:0-52 11:12-18

复现方式:将对应仓库切换到@problem/specific_loader-1分支即可重现问题。

内容的提问来源于stack exchange,提问作者Takeshi Tokugawa YD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:37:10