3

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

Dan Mindru
  • 5,986
  • 4
  • 28
  • 42
Brian
  • 1,026
  • 1
  • 15
  • 25

1 Answers1

4

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);
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Is this possible with Babel standalone? template doesn't seem to be available in version 7.12.9 – cbutler Jan 14 '21 at 22:04
  • @cbutler Are you pulling `babel` from the first param of the plugin function like the OP is? It should be available there for standalone too I'd expect. – loganfsmyth Jan 14 '21 at 22:12
  • My code is a bit different than the OP. I could add it as an answer here but someone would probably yell at me for that or I could create a new question. But when I check Babel in the console it is not on the Babel object – cbutler Jan 14 '21 at 22:19
  • I created my own question here is anyone is keen to help (would be greatly appreciated) https://stackoverflow.com/questions/65727830/babel-plugin-error-dont-use-path-replacewith-with-a-source-string-use-pa – cbutler Jan 14 '21 at 22:30