Babel: replaceWithSourceString giving Unexpected token (1:1)

限于喜欢 提交于 2021-02-10 06:50:32

问题


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"')

            }
        }
    }
}

This gives an error of

SyntaxError: src/boom.js: Unexpected token (1:1) - make sure this is an expression.
> 1 | (import all from "./logic/all")

The problem is that replaceWithSourceString is wrapping the string in rounded braces.

If I change the replaceWithSourceString to

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

and this works.. ¯_(ツ)_/¯

Any and all help you be great


回答1:


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);


来源:https://stackoverflow.com/questions/54771086/babel-replacewithsourcestring-giving-unexpected-token-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!