Blame view

build/vite/plugin/transform/globby/index.ts 7.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Modified from
// https://github.com/luxueyan/vite-transform-globby-import/blob/master/src/index.ts

// TODO Deleting files requires re-running the project
import { join } from 'path';
import { lstatSync } from 'fs';
import glob from 'glob';
import globrex from 'globrex';
import dotProp from 'dot-prop';
import { createResolver, Resolver } from 'vite/dist/node/resolver.js';
import { Transform } from 'vite/dist/node/transform.js';

const modulesDir: string = join(process.cwd(), '/node_modules/');

interface SharedConfig {
  root?: string;
  alias?: Record<string, string>;
  resolvers?: Resolver[];

  includes?: string[];
}

function template(template: string) {
  return (data: { [x: string]: any }) => {
    return template.replace(/#([^#]+)#/g, (_, g1) => data[g1] || g1);
  };
}

// TODO support hmr
function hmr(isBuild = false) {
  if (isBuild) return '';
  return `
  if (import.meta.hot) {
    import.meta.hot.accept();
  }`;
}

// handle includes
function fileInclude(includes: string | string[] | undefined, filePath: string) {
  return !includes || !Array.isArray(includes)
    ? true
    : includes.some((item) => filePath.startsWith(item));
}

// Bare exporter
function compareString(modify: any, data: string[][]) {
  return modify ? '\n' + data.map((v) => `${v[0]}._path = ${v[1]}`).join('\n') : '';
}

function varTemplate(data: string[][], name: string) {
  //prepare deep data (for locales)
  let deepData: Record<string, object | string> = {};
  let hasDeepData = false;

  //data modify
  data.map((v) => {
    //check for has deep data
    if (v[0].includes('/')) {
      hasDeepData = true;
    }

    // lastKey is a data
    let pathValue = v[0].replace(/\//g, '.').split('.');
vben authored
64
65
66
    // let scopeKey = '';
    //   const len=pathValue.length
    //   const scope=pathValue[len-2]
67
68
69
70
    let lastKey: string | undefined = pathValue.pop();

    let deepValue: Record<any, any> = {};
    if (lastKey) {
vben authored
71
72
73
74
75
76
      // Solve the problem of files with the same name in different folders
      const lastKeyList = lastKey.replace('_' + pathValue[0], '').split('_');
      const key = lastKeyList.pop();
      if (key) {
        deepValue[key] = lastKey;
      }
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    }
    // Set Deep Value
    deepValue = Object.assign(deepValue, dotProp.get(deepData, pathValue.join('.')));
    dotProp.set(deepData, pathValue.join('.'), deepValue);
  });

  if (hasDeepData) {
    return `const ${name} = ` + JSON.stringify(deepData).replace(/\"|\'/g, '');
  }

  return `const ${name} = { ${data.map((v) => v[0]).join(',')} }`;
}

const globTransform = function (config: SharedConfig): Transform {
  const resolver = createResolver(
    config.root || process.cwd(),
    config.resolvers || [],
    config.alias || {}
  );
  const { includes } = config;
  const cache = new Map();
  const urlMap = new Map();
  return {
    test({ path }) {
      const filePath = path.replace('\u0000', ''); // why some path startsWith '\u0000'?

      try {
        return (
          !filePath.startsWith(modulesDir) &&
          /\.(vue|js|jsx|ts|tsx)$/.test(filePath) &&
          fileInclude(includes, filePath) &&
          lstatSync(filePath).isFile()
        );
      } catch {
        return false;
      }
    },
    transform({ code, path, isBuild }) {
      let result = cache.get(path);
      if (!result) {
        const reg = /import\s+([\w\s{}*]+)\s+from\s+(['"])globby(\?locale)?(\?path)?!([^'"]+)\2/g;
        const match = code.match(reg);
        if (!match) return code;
        const lastImport = urlMap.get(path);
        if (lastImport && match) {
          code = code.replace(lastImport, match[0]);
        }
        result = code.replace(
          reg,
          (
            _,
            // variable to export
            exportName,
            // bare export or not
            bareExporter,
            // is locale import
            isLocale,
            // inject _path attr
            injectPath,
            // path export
            globPath
          ) => {
            const filePath = path.replace('\u0000', ''); // why some path startsWith '\u0000'?
            // resolve path

            const resolvedFilePath = globPath.startsWith('.')
              ? resolver.resolveRelativeRequest(filePath, globPath)
              : { pathname: resolver.requestToFile(globPath) };

            const files = glob.sync(resolvedFilePath.pathname, { dot: true });

            let templateStr = 'import #name# from #file#'; // import default
            let name = exportName;
            const m = exportName.match(/\{\s*(\w+)(\s+as\s+(\w+))?\s*\}/); // import module
            const m2 = exportName.match(/\*\s+as\s+(\w+)/); // import * as all module
            if (m) {
              templateStr = `import { ${m[1]} as #name# } from #file#`;
              name = m[3] || m[1];
            } else if (m2) {
              templateStr = 'import * as #name# from #file#';
              name = m2[1];
            }

            const templateRender = template(templateStr);

            const groups: Array<string>[] = [];
            const replaceFiles = files.map((f, i) => {
vben authored
164
165
              const filePath = resolver.fileToRequest(f);
              const file = bareExporter + filePath + bareExporter;
166
167
168
169
170
171

              if (isLocale) {
                const globrexRes = globrex(globPath, { extended: true, globstar: true });

                // Get segments for files like an en/system ch/modules for:
                // ['en', 'system'] ['ch', 'modules']
vben authored
172
173
174

                // TODO The window system and mac system path are inconsistent?
                const fileNameWithAlias = filePath.replace(/^(\/src\/)/, '/@/');
175
176
177
178
                const matchedGroups = globrexRes.regex.exec(fileNameWithAlias);

                if (matchedGroups && matchedGroups.length) {
                  const matchedSegments = matchedGroups[1]; //first everytime "Full Match"
vben authored
179
180
181
182
183
184
185
186
187
                  const matchList = matchedSegments.split('/').filter(Boolean);
                  const lang = matchList.shift();
                  const scope = matchList.pop();

                  // Solve the problem of files with the same name in different folders
                  const scopeKey = scope ? `${scope}_` : '';
                  const fileName = matchedGroups[2];
                  const name = scopeKey + fileName + '_' + lang;
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                  //send deep way like an (en/modules/system/dashboard) into groups
                  groups.push([matchedSegments + name, file]);
                  return templateRender({
                    name,
                    file,
                  });
                }
              } else {
                groups.push([name + i, file]);
                return templateRender({ name: name + i, file });
              }
            });
            // save in memory used result
            const filesJoined = replaceFiles.join('\n');

            urlMap.set(path, filesJoined);
vben authored
204
205
206
207

            // console.log('======================');
            // console.log(filesJoined, varTemplate(groups, name));
            // console.log('======================');
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
            return [
              filesJoined,
              compareString(injectPath, groups),
              varTemplate(groups, name),
              '',
            ].join('\n');
          }
        );
        if (isBuild) cache.set(path, result);
      }
      return `${result}${hmr(isBuild)}`;
    },
  };
};
export default globTransform;