问题描述
编辑/更新:
我已经接受了 loganfsmyth 的建议,并将 babel 作为 sveltify 函数的第一个参数,我可以访问 / 控制台日志 babel.template.statement.ast 但是,如果我尝试调用该函数,我的应用程序将无限期挂起。
>细节:
我正在尝试将其与 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);
}
}
}
});
和我的 babel 选项:
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;
}
解决方法
我认为问题在于我调用 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);
}
}
}
});