Babel:replaceWithSourceString出现意外标记(1:1)

3
我正在尝试动态替换“import”语句。
以下是一个例子,检查导入是否以 Plus 结尾。
module.exports = function(babel) {

    return {
        visitor: {
            ImportDeclaration: function(path, state) {
             // import abc from "./logic/+"
             if( ! path.node.source.value.endsWith("/+"))
              return;

             path.replaceWithSourceString('import all from "./logic/all"')

            }
        }
    }
}

这会导致错误。
SyntaxError: src/boom.js: Unexpected token (1:1) - make sure this is an expression.
> 1 | (import all from "./logic/all")

问题在于replaceWithSourceString将字符串用圆括号包裹起来。

如果我将replaceWithSourceString更改为

path.replaceWithSourceString('console.log("Hi")')

这个有效... ¯_(ツ)_/¯

任何帮助都将是伟大的。

1个回答

4

replaceWithSourceString 应该尽量避免使用,因为正如您所看到的,它并不是一个非常好的API。推荐的方法是使用 template 创建要插入脚本的AST。假设这是针对Babel 7.x的,您可以执行以下操作:

const importNode = babel.template.statement.ast`import all from "./logic/all"`;
path.replaceWith(importNode);

这在Babel独立版是可行的吗?在7.12.9版本中似乎没有模板(template)。 - cbutler
@cbutler,你是从插件函数的第一个参数中提取babel吗?我认为它应该在独立模式下也是可用的。 - loganfsmyth
我的代码与 OP 的有点不同。我可以将其添加为答案,但可能会有人因此而责备我,或者我可以创建一个新的问题。但是当我在控制台中检查 Babel 时,它不在 Babel 对象上。 - cbutler
我在这里创建了自己的问题,如果有人愿意帮忙(将不胜感激):https://stackoverflow.com/questions/65727830/babel-plugin-error-dont-use-path-replacewith-with-a-source-string-use-pa - cbutler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接