如何解决自定义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
相关产品推荐
相关产品推荐

