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

∥☆過路亽.° 提交于 2021-01-29 20:06:10

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/65727830/babel-plugin-error-dont-use-path-replacewith-with-a-source-string-use-pa

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