简体   繁体   中英

Babel plugin error: Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`

EDIT / UPDATE:

I have taken loganfsmyth's advice and pulled out babel as the first argument to the sveltify function and I can access / console log babel.template.statement.ast however, if I try to call that function my app hangs indefinitely.

Thie details:

I am trying to use this with svelte to replace the import statement and I have a plugin as:

const sveltify = (babel) => ({
  visitor: {
    ImportDeclaration(path){
      // import x from 'svelte/somewhere'
      if (path.node.source.value.startsWith("svelte/")) {
        const specifiers = path.node.specifiers.map(s => ` ${s.local.name}` );
        const importee = path.node.source.value.replace('/', '.');

        // this line works without babel.template.statement.ast but gives the error in the question title
        // adding babel.template.statement.ast causes the app to hang indefinitely 
        const importNode = babel.template.statement.ast`const {${specifiers} } = ${importee};`;

        path.replaceWith(importNode);
      }
    }
  }
});

and my babel options:

const SVELTE_OPTIONS = {
  presets: [
    // [
    //   Babel.availablePresets['env'],
    //   {
    //     useBuiltIns: 'usage',
    //     corejs: 3,
    //   }
    // ],
    ['es2017', { 'modules': false }],
  ],
  plugins: [
    sveltify,
    'transform-modules-commonjs',
    'transform-destructuring',
    'proposal-object-rest-spread',
  ],
};

And finally I am using that in my code later on a call to transform like this:

// simplified
function transpile(moduleCode) {
  const { code } = Babel.transform(moduleCode, SVELTE_OPTIONS);
  return code;
}

The other question you linked is pulling babel out of the first param of the plugin, and you should be doing the same, so

const sveltify = () => ({

should be

const sveltify = (babel) => ({

then you can use babel.template from that object.

I think the problem was in the way I was calling ast. The following works:

const sveltify = (babel) => ({
  visitor: {
    ImportDeclaration(path){
      // import x from 'svelte/somewhere'
      if (path.node.source.value.startsWith("svelte/")) {
        const specifiers = path.node.specifiers.map(s => ` ${s.local.name}` );
        const importee = path.node.source.value.replace('/', '.');
        const tmpNode = `const {${specifiers} } = ${importee};`;
        const importNode = babel.template.statement.ast(tmpNode);

        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