-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite-plugin-import-maps.ts
285 lines (235 loc) · 9.25 KB
/
vite-plugin-import-maps.ts
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
64
65
66
67
68
69
70
71
72
73
74
75
76
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// vite-plugin-import-maps.ts
import { existsSync, readFileSync } from 'fs';
import { ConfigEnv, Plugin } from 'vite';
import { fileURLToPath, URL } from 'node:url';
import externalize from 'vite-plugin-externalize-dependencies';
import { resolve, basename, join as joinOrig } from 'path';
import chalk from 'chalk';
import { NormalizedOutputOptions, OutputBundle, PreRenderedAsset, PreRenderedChunk } from 'rollup';
// console.log('[vite-plugin-import-maps] baseUrl:', baseUrl);
let baseUrl = undefined;
function join(...paths: string[]): string {
return joinOrig(...paths).replaceAll('\\', '/');
}
export interface ImportMapsConfig {
entryTemplate: string;
assetTemplate: string;
chunckTemplate: string;
importMaps: {
type?: string;
modules?: string[];
dev?: string[];
build?: string[];
};
}
export interface ImportMap {
imports: { [key: string]: string };
scopes?: { [key: string]: { [key: string]: string } };
}
function loadImportMapFiles(devMode: boolean, config: ImportMapsConfig): ImportMap[] {
const devImportMapFiles: string[] = config.importMaps.dev;
const buildImportMapFiles: string[] = config.importMaps.build;
const modulesImportMapFile: string[] = config.importMaps.modules;
let importMapFiles: string[] = devMode
? [...devImportMapFiles, ...modulesImportMapFile]
: [...buildImportMapFiles, ...modulesImportMapFile];
console.log(`[vite-plugin-import-maps] baseUrl:${baseUrl} import-map-files:${importMapFiles} devMode:${devMode}`);
const importMaps: ImportMap[] = [];
for (const filename of importMapFiles) {
if (existsSync(filename)) {
const importMap: ImportMap = JSON.parse(readFileSync(filename, { encoding: 'utf8' }));
importMaps.push(importMap);
} else {
console.error('[vite-plugin-import-maps] Import map not found:', filename);
}
}
return importMaps;
}
function joinImportMaps(maps: ImportMap[]): ImportMap {
const importMap: ImportMap = { imports: {}, scopes: {} };
for (const map of maps) {
for (const key of Object.keys(map.imports)) {
importMap.imports[key] = map.imports[key];
}
if (map.scopes) {
for (const key of Object.keys(map.scopes)) {
importMap.scopes[key] = {
...importMap.scopes[key],
...map.scopes[key],
};
}
}
}
return importMap;
}
const printedModules = new Set<string>();
export const defaultImportMapsConfig : ImportMapsConfig = {
importMaps: {
modules: ['config/importMap.modules.json'],
dev: ['config/importMap.dev.json'],
build: ['config/importMap.build.json'],
type: 'importmap',
},
entryTemplate: '[name]-[hash].[ext]',
assetTemplate: 'assets/[name]-[hash].[ext]',
chunckTemplate: 'assets/[name]-[hash].js',
} as ImportMapsConfig;
export function ImportMapsPlugin(pluginConfig: ImportMapsConfig = defaultImportMapsConfig): Plugin {
// console.log('[vite-plugin-import-maps] ImportMapsPlugin.init ...');
let devMode = true;
let importMapSrc: ImportMap = {
imports: {},
scopes: {}
};
let importMap: ImportMap = {
imports: {},
scopes: {}
};
let externalDependencies: string[] = [];
let inputs: { [name: string]: string } = {};
let inputKeysSet: Set<string> = new Set();
function updateImportMaps() {
const importMaps: ImportMap[] = loadImportMapFiles(devMode, pluginConfig);
importMapSrc = joinImportMaps(importMaps);
importMap = { imports: { ...importMapSrc.imports }, scopes: { ...importMapSrc.scopes } };
externalDependencies = Object.keys(importMap.imports);
inputs = {};
const indexPath = resolve('index.html');
if (existsSync(indexPath)) {
console.log(`[vite-plugin-import-maps] adding entry point: ${indexPath}`);
inputs.index = indexPath;
} else {
console.log(`[vite-plugin-import-maps] skipping entry point: ${indexPath}`);
}
Object.entries(importMap.imports).forEach(([k, v]) => {
if (v.startsWith('http://') || v.startsWith('https://')) {
if (v.startsWith('http://@/')) {
importMap.imports[k] = v.replace('http://@/', '/');
}
else if (v.startsWith('https://@/')) {
importMap.imports[k] = v.replace('https://@/', '/');
}
return;
}
inputs[k] = v;
});
const inputKeysArray = Object.keys(inputs);
inputKeysSet = new Set(inputKeysArray);
}
function useBaseUrlInImportMap() {
for (const [moduleName, moduleUrl] of Object.entries(importMap.imports)) {
if (moduleUrl.startsWith('/')) {
const newModuleUrl = join(baseUrl, importMapSrc.imports[moduleName]);
importMap.imports[moduleName] = newModuleUrl;
}
}
}
function isExternal(moduleName: string): boolean {
const isExternalModule = externalDependencies.some(dep =>
moduleName === dep ||
moduleName.startsWith(dep + '/') ||
moduleName.startsWith('http://') ||
moduleName.startsWith('https://')
);
const aliasPath = moduleName
.replace(fileURLToPath(new URL('./', import.meta.url)), '/')
.replace('@/', '/src/');
if (!printedModules.has(aliasPath)) {
printedModules.add(aliasPath);
console.log(chalk.bold.blueBright(`[${isExternalModule ? 'external' : 'internal'}]`), chalk.magentaBright(aliasPath));
}
return isExternalModule;
}
return {
name: 'vite-plugin-import-map',
config(config: any, env: ConfigEnv) {
devMode = env.command === 'serve';
baseUrl = config.base;
updateImportMaps();
// console.log('[vite-plugin-import-maps] ImportMapsPlugin.config ...', importMap);
if (externalDependencies.length > 0) {
return {
resolve: {
alias: importMap.imports,
},
plugins: [
externalize({
externals: [isExternal],
}),
],
build: {
target: 'esnext',
// assetsInlineLimit: 0,
rollupOptions: {
external: isExternal,
preserveEntrySignatures: 'strict',
input: inputs,
output: {
entryFileNames: (chunkInfo: {
exports: string[];
facadeModuleId: string | null;
isDynamicEntry: boolean;
isEntry: boolean;
isImplicitEntry: boolean;
moduleIds: string[];
name: string;
type: 'chunk';
}) => {
const chunkName: string = chunkInfo.name;
console.log(chalk.blue.bold('[entry]'), chalk.magenta(chunkName), chalk.cyanBright(chunkInfo.facadeModuleId));//, chunkInfo);
if (inputKeysSet.has(chunkName)) {
return pluginConfig.chunckTemplate.replace('[name]', basename(chunkName));
// return `assets/${basename(chunkName)}-[hash].js`;
}
return pluginConfig.entryTemplate;
},
chunkFileNames(chunkInfo: PreRenderedChunk): string {
const chunkName: string = chunkInfo.name;
console.log(chalk.blue.bold('[chunkFileNames]'), chalk.magenta(chunkName), chunkInfo.facadeModuleId);//, chunkInfo);
if (chunkName.includes('_')) {
let updatedChunkName = chunkName;
// if (updatedChunkName.startsWith('_')) {
// updatedChunkName = chunkName.substring(1);
// }
updatedChunkName = updatedChunkName.replaceAll('_', '--');
return pluginConfig.chunckTemplate.replace('[name]', updatedChunkName);
// return `assets/${updatedChunkName}-[hash].js`;
}
return pluginConfig.chunckTemplate;
},
assetFileNames: (chunkInfo: PreRenderedAsset) : string => {
console.log(chalk.blue.bold('[assetFileNames]'), chalk.magenta(chunkInfo.name));//, chalk.cyanBright(chunkInfo.source), chunkInfo);
return pluginConfig.assetTemplate;
},
},
},
},
};
}
return {};
},
transformIndexHtml: {
order: 'post' as const,
async handler(html: string, ctx: { path: string; filename: string }) {
// console.log('transformIndexHtml', 'filename:', ctx.filename, 'path:', ctx.path);
if (externalDependencies.length > 0) {
if (devMode) {
useBaseUrlInImportMap(); // in build mode it is updated inside generateBundle
}
const importMapAsString = `<script type="${pluginConfig.importMaps?.type ?? 'importmap'}">\n${JSON.stringify(importMap, null, 2)}\n</script>`;
return html.replace('</head>', `${importMapAsString}\n </head>`);
}
return html;
},
},
generateBundle(options: NormalizedOutputOptions, bundle: OutputBundle, isWrite: boolean) {
Object.entries(bundle).forEach(([fileName, file]) => {
const name: string = file.name;
if (inputKeysSet.has(name) && importMap.imports[name]) {
console.log(chalk.blue.bold('[map-import]'), chalk.magenta(name), chalk.greenBright(fileName), chalk.cyanBright(importMap.imports[name]));
importMap.imports[name] = join(baseUrl, fileName);
}
});
},
};
}