65 lines
2.8 KiB
JavaScript
65 lines
2.8 KiB
JavaScript
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')));
|
||
}
|
||
|
||
}
|
||
}
|
||
}
|
||
};
|
||
};
|
||
|