replaceWithSourceString

replaceWithSourceString

本文介绍了Babel:replaceWithSourceString提供意外令牌(1:1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态替换导入"语句.

I am trying to replace dynamically "import" statements.

下面是检查导入是否以加号结尾的示例.

Here is an example that checks if the import ends with a 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更改为

If I change the replaceWithSourceString to

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

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

任何人都可以帮助您变得很棒

Any and all help you be great

推荐答案

replaceWithSourceString ,因为正如您所看到的那样,它并不是一个很好的API.创建用于插入脚本的AST的推荐方法是使用 template .假设这是针对Babel 7.x的,您可以做到

replaceWithSourceString should really be avoided, because it is just not a very good API, as you are seeing. The recommended approach for creating ASTs to insert into the script is to use template. Assuming this is for Babel 7.x, you can do

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

这篇关于Babel:replaceWithSourceString提供意外令牌(1:1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 01:39