Babel:replaceWithSourceString 给出意外的令牌 (1:1)
Babel: replaceWithSourceString giving Unexpected token (1:1)
我正在尝试动态替换 "import" 语句。
这是一个检查导入是否以加号结尾的示例。
module.exports = function(babel) {
return {
visitor: {
ImportDeclaration: function(path, state) {
// import abc from "./logic/+"
if( ! path.node.source.value.endsWith("/+"))
return;
path.replaceWithSourceString('import all from "./logic/all"')
}
}
}
}
这给出了
的错误
SyntaxError: src/boom.js: Unexpected token (1:1) - make sure this is an expression.
> 1 | (import all from "./logic/all")
问题是replaceWithSourceString is wrapping the string in rounded braces.
如果我将 replaceWithSourceString 更改为
path.replaceWithSourceString('console.log("Hi")')
这有效.. ¯_(ツ)_/¯
任何和所有帮助你变得伟大
replaceWithSourceString
真的应该避免,因为它不是很好的 API,如您所见。创建 AST 以插入脚本的推荐方法是使用 template
。假设这是针对 Babel 7.x,你可以做
const importNode = babel.template.statement.ast`import all from "./logic/all"`;
path.replaceWith(importNode);
我正在尝试动态替换 "import" 语句。
这是一个检查导入是否以加号结尾的示例。
module.exports = function(babel) {
return {
visitor: {
ImportDeclaration: function(path, state) {
// import abc from "./logic/+"
if( ! path.node.source.value.endsWith("/+"))
return;
path.replaceWithSourceString('import all from "./logic/all"')
}
}
}
}
这给出了
的错误SyntaxError: src/boom.js: Unexpected token (1:1) - make sure this is an expression.
> 1 | (import all from "./logic/all")
问题是replaceWithSourceString is wrapping the string in rounded braces.
如果我将 replaceWithSourceString 更改为
path.replaceWithSourceString('console.log("Hi")')
这有效.. ¯_(ツ)_/¯
任何和所有帮助你变得伟大
replaceWithSourceString
真的应该避免,因为它不是很好的 API,如您所见。创建 AST 以插入脚本的推荐方法是使用 template
。假设这是针对 Babel 7.x,你可以做
const importNode = babel.template.statement.ast`import all from "./logic/all"`;
path.replaceWith(importNode);