oak-cli/config/babel-plugin/reuse-oak-component.js

65 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const t = require('@babel/types');
const generate = require('@babel/generator').default;
const { relative, dirname, parse, join } = require('path');
const fs = require('fs');
const { getStatements } = require('../utils/injectGetRender');
module.exports = (babel) => {
return {
visitor: {
ExportDefaultDeclaration(path, state) {
const { declaration } = path.node;
const { cwd, filename } = state;
const { base } = parse(filename);
if (['index.ts', 'index.js'].includes(base) && t.isIdentifier(declaration) && declaration.name === 'OakComponent') {
const dir = dirname(filename);
const statements = getStatements(dir);
const resetRenderFunction = t.functionExpression(
null, // 可选的函数名称
[], // 参数列表
t.blockStatement([
...statements
])
);
const newComponent = t.arrowFunctionExpression(
[t.identifier('props')],
t.blockStatement([
t.returnStatement(
t.callExpression(
t.memberExpression(t.identifier('React'), t.identifier('createElement')),
[
t.identifier('OakComponent'),
t.objectExpression([
t.spreadElement(t.identifier('props')),
// #开头的不是identifier而是StringLiteral
t.objectProperty(t.stringLiteral('#resetRender'), resetRenderFunction)
])
]
)
)
])
);
// 输出一下生成的内容:
// const { code } = generate(newComponent);
// console.log(code);
path.replaceWith(
t.exportDefaultDeclaration(newComponent)
);
// 先判断有没有import React没有的话插入
if (!path.findParent(t.File).node.body.some(node => t.isImportDeclaration(node) && node.source.value === 'react')) {
path.insertBefore(t.importDeclaration([t.importDefaultSpecifier(t.identifier('React'))], t.stringLiteral('react')));
}
}
}
}
};
};