transformFinalCode.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Components that need to be converted
  2. export const DEFAULT_Components = new Set(['scroll-view']);
  3. //whether to include the path to the current file
  4. export const judgePath = (paths: string[], targetPath: string) => {
  5. for (let i = 0; i < paths.length; i++) {
  6. let reg = new RegExp(paths[i]);
  7. if (reg.test(targetPath)) {
  8. return true;
  9. }
  10. }
  11. return false;
  12. };
  13. import type { Plugin } from 'vite';
  14. export interface transformOptions {
  15. exclude?: string[];
  16. components?: string[];
  17. envCondition?: string;
  18. include?: string[];
  19. }
  20. export function transformFinalCode(options: transformOptions = {}): Plugin {
  21. let _options: transformOptions = {
  22. envCondition: 'process.env.TARO_ENV',
  23. components: [],
  24. include: [],
  25. exclude: []
  26. };
  27. _options = Object.assign(_options, options);
  28. return {
  29. name: 'transformFinalCode',
  30. enforce: 'post',
  31. async config(config) {
  32. if (!_options.envCondition) {
  33. throw new Error('Environment variable is missing, check the envCondition field');
  34. }
  35. let _define = {};
  36. _define[_options.envCondition] = _options.envCondition;
  37. config.define = Object.assign(config.define, _define);
  38. return config;
  39. },
  40. transform(code: string, id: any) {
  41. let _code = code;
  42. let _components = DEFAULT_Components;
  43. if (_options.components && _options.components.length > 0) {
  44. _components = new Set(_options.components);
  45. }
  46. if (_options.exclude && _options.exclude.length !== 0 && judgePath(_options.exclude, id)) {
  47. return _code;
  48. }
  49. if (_options.include && _options.include.length !== 0 && !judgePath(_options.include, id)) {
  50. return _code;
  51. }
  52. _components.forEach((tagName) => {
  53. let Reg = new RegExp(`"${tagName}"`, 'ig');
  54. const r = `function(){if(${_options.envCondition} === 'h5'){return 'taro-${tagName}'}else{return '${tagName}'}}()`;
  55. _code = _code.replace(Reg, r);
  56. });
  57. return _code;
  58. }
  59. };
  60. }