createPkgDeclare.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const fs = require('fs');
  2. const path = require('path');
  3. const t = require('@babel/types');
  4. const {parse} = require('@babel/parser');
  5. const {default: traverse} = require('@babel/traverse');
  6. const {default: generate} = require('@babel/generator');
  7. const PKGS = 'packages';
  8. const emptyLine = '/*hr*/';
  9. const nutMainFile = path.join(__dirname, '../src/nutui.js');
  10. const nutTypings = path.join(__dirname, '../types/nutui.d.ts');
  11. function transformCodes(codes, visitor) {
  12. const ast = parse(codes, {
  13. sourceType: "module"
  14. });
  15. traverse(ast, visitor);
  16. const {code} = generate(ast, { /* options */ }, codes);
  17. return code;
  18. }
  19. function insertImports(pkg) {
  20. const lowername = pkg.toLowerCase();
  21. this.insertBefore(
  22. t.importDeclaration([
  23. t.importDefaultSpecifier(t.identifier(pkg))
  24. ],
  25. t.stringLiteral(`./packages/${lowername}/index.js`))
  26. );
  27. this.insertBefore(
  28. t.importDeclaration([], t.stringLiteral(`./packages/${lowername}/${lowername}.scss`))
  29. );
  30. this.insertBefore(t.stringLiteral(emptyLine));
  31. }
  32. function createProp(pkg) {
  33. return t.objectProperty(t.identifier(pkg), t.identifier(pkg));
  34. }
  35. function addToExport(pkg, init) {
  36. init.properties.push(createProp(pkg));
  37. this.replaceWith(t.variableDeclaration('const', [
  38. t.variableDeclarator(t.identifier(PKGS), init)
  39. ]));
  40. }
  41. function addPkgDeclare(pkg) {
  42. const codes = fs.readFileSync(nutMainFile).toString();
  43. const visitor = {
  44. VariableDeclaration: function(p) {
  45. const {node} = p;//console.log(Object.keys(p.__proto__))
  46. if(node) {
  47. const {declarations = []} = node;
  48. if(declarations.length) {
  49. for(const {id, init} of declarations) {
  50. if(id.name === PKGS && init.properties && init.properties.length) {
  51. const props = init.properties.filter(({key}) => key.name.toLowerCase() === pkg.toLowerCase());
  52. if(!props.length) {
  53. insertImports.call(p, pkg);
  54. addToExport.call(p, pkg, init);
  55. p.insertAfter(t.stringLiteral(emptyLine));
  56. p.stop();
  57. break;
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }
  65. const code = transformCodes(codes, visitor);
  66. return code;
  67. }
  68. function createPkgDeclare(pkg) {
  69. const code = addPkgDeclare(pkg);
  70. fs.writeFileSync(nutMainFile, code.replace(/"\/\*hr\*\/"/g, ''));
  71. fs.appendFileSync(nutTypings, `export declare class ${pkg} extends UIComponent {}\n`);
  72. }
  73. module.exports = createPkgDeclare;