详细信息:我正在尝试使用svelte替换导入语句,并且我有一个插件为: const sveltify =(babel)=>({访客:{ImportDeclaration(path){//从'svelte/somewhere'导入x如果(path.node.source.value.startsWith("svelte/")){const specifiers = path.node.specifiers.map(s =>`$ {s.local.name}`);const importee = path.node.source.value.replace('/','.');//此行在没有babel.template.statement.ast的情况下有效,但在问题标题中给出了错误//添加babel.template.statement.ast导致应用无限期挂起const importNode = babel.template.statement.ast`const {$ {specifiers}} = $ {importee};`;path.replaceWith(importNode);}}}}); 和我的通天选项: const SVELTE_OPTIONS = {预设:[//[//Babel.availablePresets ['env'],//{//useBuiltIns:'用法',//corejs:3,//}//],['es2017',{'modules':false}],],插件:[美化,'transform-modules-commonjs',转型破坏",提案对象休息传播",],}; 最后,我稍后在代码中使用它来进行如下转换: //简化函数transpile(moduleCode){const {code} = Babel.transform(moduleCode,SVELTE_OPTIONS);返回码;} 解决方案您链接的另一个问题是将 babel 从插件的第一个参数中拉出,您应该这样做,所以 const sveltify =()=>({ 应该是 const sveltify =(babel)=>({ 然后您可以从该对象使用 babel.template .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:// simplifiedfunction 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, soconst sveltify = () => ({should beconst sveltify = (babel) => ({then you can use babel.template from that object. 这篇关于Babel插件错误:请勿将`path.replaceWith()`与源字符串一起使用,而应使用`path.replaceWithSourceString()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-30 09:12