简体   繁体   中英

Babel: replaceWithSourceString giving Unexpected token (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"')

            }
        }
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM