[英]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.我接受了 loganfsmyth 的建议并将 babel 作为 sveltify function 的第一个参数,并且我可以访问/控制台日志 babel.template.statement.ast 但是,如果我尝试调用 function 我的应用程序将无限期挂起。
Thie details:详细信息:
I am trying to use this with svelte to replace the import statement and I have a plugin as:我正在尝试将它与 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);
}
}
}
});
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您链接的另一个问题是将babel
从插件的第一个参数中拉出,您应该这样做,所以
const sveltify = () => ({
should be应该
const sveltify = (babel) => ({
then you can use babel.template
from that object.然后你可以使用babel.template
中的 babel.template。
I think the problem was in the way I was calling ast.我认为问题在于我调用 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);
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.