我是babel的新手,正在构建一个库,我希望人们使用我的宏导入我的库,以便他们获得基于环境的优化版本,我知道我可以通过使用条件{{1 }},但我想使用es6导出来实现module.exports
。
所以我想做以下事情:
tree-shaking
上面的代码如下。
import { sum, add } from 'myLibrary/macro'; // I'm going to change this line
import otherLibrary from 'otherLibrary/macro';
sum([1,2,3])
现在,我写了一个普通的babel版本:
import { sum, add } from "myLibrary/production"; // `macro` keyword replaced
import otherLibrary from 'otherLibrary/macro';
sum([1, 2, 3]);
我只需返回一个export default function(babel) {
return {
visitor: {
// All my `ImportDeclaration` gets processed.
ImportDeclaration(path) {
if (path.node.source.value.includes("myLibrary")) {
const someCondition = true; // I actually want to use `process.env.NODE_ENV === "production"`
if (someCondition) {
path.node.source.value = "myLibrary/production";
} else {
path.node.source.value = "myLibrary/development";
}
}
}
}
};
}
对象就可以轻松运行我的条件,并且我所有的visitor
都得到了处理,但是在ImportDeclaration
中,似乎无法轻松实现:
babel macros
有什么简单的方法可以在module.exports = createMacro(myMacro);
function myMacro({ references, state, babel }) {
const someCondition = true; // I actually want to use `process.env.NODE_ENV === "production"`
state.file.path.node.body.forEach(node => { // I need to `forEach` by my self.
if (node.type === "ImportDeclaration") {
if (node.source.value.includes("myLibrary")) {
if (someCondition) {
node.source.value = "myLibrary/production";
} else {
node.source.value = "myLibrary/development";
}
}
}
});
return { keepImports: true };
}
中实现相同的目的?