processLib.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Porcess generated lib files.
  2. // Like adding js extension in the import statement.
  3. const { transformImport } = require('./transformImport');
  4. const globby = require('globby');
  5. const path = require('path');
  6. const fs = require('fs');
  7. const chalk = require('chalk');
  8. const rollup = require('rollup');
  9. const nodeResolve = require('@rollup/plugin-node-resolve').default;
  10. function addJsExtension(moduleName) {
  11. // Ignore 'tslib'
  12. if (!(moduleName.startsWith('.'))) {
  13. return moduleName;
  14. }
  15. if (moduleName.endsWith('.ts')) {
  16. // Replace ts with js
  17. return moduleName.replace(/\.ts$/, '.js');
  18. }
  19. else if (moduleName.endsWith('.js')) {
  20. return moduleName;
  21. }
  22. else {
  23. return moduleName + '.js'
  24. }
  25. }
  26. async function transform() {
  27. const libFiles = await globby([
  28. '**/*.js'
  29. ], {
  30. cwd: path.join(__dirname, '../lib'),
  31. absolute: true
  32. });
  33. if (libFiles.length === 0) {
  34. throw new Error('No lib files found.')
  35. }
  36. for (let file of libFiles) {
  37. const code = fs.readFileSync(file, 'utf-8');
  38. fs.writeFileSync(file, transformImport(code, addJsExtension), 'utf-8');
  39. }
  40. // Transform index;
  41. const indexFile = path.join(__dirname, '../index.js');
  42. fs.writeFileSync(
  43. indexFile,
  44. transformImport(
  45. fs.readFileSync(indexFile, 'utf-8'),
  46. (mduleName) => addJsExtension(mduleName).replace('./src', './lib')
  47. )
  48. )
  49. }
  50. transform().then(() => {
  51. console.log(chalk.green('Added .js extensions.'));
  52. console.log(chalk.gray('Start testing generated libs...'));
  53. }).then(() => {
  54. return rollup.rollup({
  55. input: path.resolve(__dirname, '../index.js'),
  56. plugins: [nodeResolve()]
  57. });
  58. }).then(() => {
  59. console.log(chalk.green('Libs can be bundled!'));
  60. });