安装
npm install --save-dev @babel/helpers
使用
直接:
import * as helpers from '@babel/helpers';
import * as t from '@babel/types';
const typeofHelper = helpers.get('typeof');
t.isExpressionStatement(typeofHelper);
// true
在一个插件中
export default {
visitor: {
UnaryExpression(path) {
// The .addHelper function adds, if needed, the helper to the file
// and returns an expression which references the helper
const typeofHelper = this.addHelper("typeof");
t.isExpression(typeofHelper); // true
}
};
定义辅助对象
注意:此软件包仅供此存储库中包含的软件包使用。目前,第三方插件无法定义助手。
助手定义在src/helpers.js文件,并且它们必须是遵循以下准则的有效模块:
-
它们必须有一个默认的导出,这是它们的入口点。
-
它们可以通过使用默认导入来导入其他辅助对象。
-
他们不能有被命名的exports。
helpers.customHelper = defineHelper(` import dep from "dependency";
const foo = 2; export default function getFooTimesDepPlusX(x) { return foo * dep() + x; }`);