问题
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