繁体   English   中英

Babel 插件错误:不要将 `path.replaceWith()` 与源字符串一起使用,请使用 `path.replaceWithSourceString()`

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

编辑/更新:

我接受了 loganfsmyth 的建议并将 babel 作为 sveltify function 的第一个参数,并且我可以访问/控制台日志 babel.template.statement.ast 但是,如果我尝试调用 function 我的应用程序将无限期挂起。

详细信息:

我正在尝试将它与 svelte 一起使用来替换导入语句,并且我有一个插件:

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

和我的通天塔选项:

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',
  ],
};

最后,我稍后在我的代码中使用它来调用转换,如下所示:

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

您链接的另一个问题是将babel从插件的第一个参数中拉出,您应该这样做,所以

const sveltify = () => ({

应该

const sveltify = (babel) => ({

然后你可以使用babel.template中的 babel.template。

我认为问题在于我调用 ast 的方式。 以下作品:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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