@vitejs/plugin-legacy 1.8.1 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,22 +27,6 @@ export default {
27
27
  }
28
28
  ```
29
29
 
30
- When targeting IE11, you also need `regenerator-runtime`:
31
-
32
- ```js
33
- // vite.config.js
34
- import legacy from '@vitejs/plugin-legacy'
35
-
36
- export default {
37
- plugins: [
38
- legacy({
39
- targets: ['ie >= 11'],
40
- additionalLegacyPolyfills: ['regenerator-runtime/runtime']
41
- })
42
- ]
43
- }
44
- ```
45
-
46
30
  ## Options
47
31
 
48
32
  ### `targets`
@@ -138,9 +122,9 @@ The legacy plugin offers a way to use native `import()` in the modern build whil
138
122
 
139
123
  Polyfill specifier strings for `polyfills` and `modernPolyfills` can be either of the following:
140
124
 
141
- - Any [`core-js` 3 sub import paths](https://unpkg.com/browse/core-js@3.8.2/) - e.g. `es/map` will import `core-js/es/map`
125
+ - Any [`core-js` 3 sub import paths](https://unpkg.com/browse/core-js@latest/) - e.g. `es/map` will import `core-js/es/map`
142
126
 
143
- - Any [individual `core-js` 3 modules](https://unpkg.com/browse/core-js@3.8.2/modules/) - e.g. `es.array.iterator` will import `core-js/modules/es.array.iterator.js`
127
+ - Any [individual `core-js` 3 modules](https://unpkg.com/browse/core-js@latest/modules/) - e.g. `es.array.iterator` will import `core-js/modules/es.array.iterator.js`
144
128
 
145
129
  **Example**
146
130
 
@@ -163,7 +147,6 @@ The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https
163
147
 
164
148
  - `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=`
165
149
  - `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=`
166
- - `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=`
167
150
  - `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=`
168
151
  - `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=`
169
152
 
package/dist/index.cjs ADDED
@@ -0,0 +1,486 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const module$1 = require('module');
8
+ const url = require('url');
9
+ const vite = require('vite');
10
+ const MagicString = require('magic-string');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
13
+
14
+ const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
15
+ const MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
16
+
17
+ let babel;
18
+ async function loadBabel() {
19
+ if (!babel) {
20
+ babel = await import('@babel/standalone');
21
+ }
22
+ return babel;
23
+ }
24
+ const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`;
25
+ const legacyPolyfillId = "vite-legacy-polyfill";
26
+ const legacyEntryId = "vite-legacy-entry";
27
+ const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
28
+ const detectModernBrowserVarName = "__vite_is_modern_browser";
29
+ const detectModernBrowserCode = `try{import(new URL(import.meta.url).href).catch(()=>1);}catch(e){}window.${detectModernBrowserVarName}=true;`;
30
+ const dynamicFallbackInlineCode = `!function(){if(window.${detectModernBrowserVarName})return;console.warn("vite: loading legacy build because dynamic import or import.meta.url is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`;
31
+ const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`;
32
+ const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
33
+ function viteLegacyPlugin(options = {}) {
34
+ let config;
35
+ const targets = options.targets || "defaults";
36
+ const genLegacy = options.renderLegacyChunks !== false;
37
+ const genDynamicFallback = genLegacy;
38
+ const debugFlags = (process.env.DEBUG || "").split(",");
39
+ const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
40
+ const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
41
+ const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
42
+ const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
43
+ const modernPolyfills = /* @__PURE__ */ new Set();
44
+ const DEFAULT_LEGACY_POLYFILL = [
45
+ "core-js/modules/es.promise",
46
+ "core-js/modules/es.array.iterator"
47
+ ];
48
+ const legacyPolyfills = new Set(DEFAULT_LEGACY_POLYFILL);
49
+ if (Array.isArray(options.modernPolyfills)) {
50
+ options.modernPolyfills.forEach((i) => {
51
+ modernPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
52
+ });
53
+ }
54
+ if (Array.isArray(options.polyfills)) {
55
+ options.polyfills.forEach((i) => {
56
+ if (i.startsWith(`regenerator`)) {
57
+ legacyPolyfills.add(`regenerator-runtime/runtime.js`);
58
+ } else {
59
+ legacyPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
60
+ }
61
+ });
62
+ }
63
+ if (Array.isArray(options.additionalLegacyPolyfills)) {
64
+ options.additionalLegacyPolyfills.forEach((i) => {
65
+ legacyPolyfills.add(i);
66
+ });
67
+ }
68
+ const legacyConfigPlugin = {
69
+ name: "vite:legacy-config",
70
+ apply: "build",
71
+ config(config2) {
72
+ if (!config2.build) {
73
+ config2.build = {};
74
+ }
75
+ if (!config2.build.cssTarget) {
76
+ config2.build.cssTarget = "chrome61";
77
+ }
78
+ }
79
+ };
80
+ const legacyGenerateBundlePlugin = {
81
+ name: "vite:legacy-generate-polyfill-chunk",
82
+ apply: "build",
83
+ async generateBundle(opts, bundle) {
84
+ if (config.build.ssr) {
85
+ return;
86
+ }
87
+ if (!isLegacyBundle(bundle, opts)) {
88
+ if (!modernPolyfills.size) {
89
+ return;
90
+ }
91
+ isDebug && console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
92
+ await buildPolyfillChunk("polyfills-modern", modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, options.externalSystemJS);
93
+ return;
94
+ }
95
+ if (!genLegacy) {
96
+ return;
97
+ }
98
+ if (legacyPolyfills.size || genDynamicFallback) {
99
+ if (!legacyPolyfills.has("es.promise")) {
100
+ await detectPolyfills(`Promise.resolve()`, targets, legacyPolyfills);
101
+ }
102
+ isDebug && console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
103
+ await buildPolyfillChunk("polyfills-legacy", legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, options.externalSystemJS);
104
+ }
105
+ }
106
+ };
107
+ const _require = module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)));
108
+ const legacyPostPlugin = {
109
+ name: "vite:legacy-post-process",
110
+ enforce: "post",
111
+ apply: "build",
112
+ configResolved(_config) {
113
+ if (_config.build.lib) {
114
+ throw new Error("@vitejs/plugin-legacy does not support library mode.");
115
+ }
116
+ config = _config;
117
+ if (!genLegacy || config.build.ssr) {
118
+ return;
119
+ }
120
+ const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy.[hash].js") => {
121
+ if (!fileNames) {
122
+ return path__default.posix.join(config.build.assetsDir, defaultFileName);
123
+ }
124
+ return (chunkInfo) => {
125
+ let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
126
+ if (fileName.includes("[name]")) {
127
+ fileName = fileName.replace("[name]", "[name]-legacy");
128
+ } else {
129
+ fileName = fileName.replace(/(.+)\.(.+)/, "$1-legacy.$2");
130
+ }
131
+ return fileName;
132
+ };
133
+ };
134
+ const createLegacyOutput = (options2 = {}) => {
135
+ return {
136
+ ...options2,
137
+ format: "system",
138
+ entryFileNames: getLegacyOutputFileName(options2.entryFileNames),
139
+ chunkFileNames: getLegacyOutputFileName(options2.chunkFileNames)
140
+ };
141
+ };
142
+ const { rollupOptions } = config.build;
143
+ const { output } = rollupOptions;
144
+ if (Array.isArray(output)) {
145
+ rollupOptions.output = [...output.map(createLegacyOutput), ...output];
146
+ } else {
147
+ rollupOptions.output = [createLegacyOutput(output), output || {}];
148
+ }
149
+ },
150
+ async renderChunk(raw, chunk, opts) {
151
+ if (config.build.ssr) {
152
+ return null;
153
+ }
154
+ if (!isLegacyChunk(chunk, opts)) {
155
+ if (options.modernPolyfills && !Array.isArray(options.modernPolyfills)) {
156
+ await detectPolyfills(raw, { esmodules: true }, modernPolyfills);
157
+ }
158
+ const ms = new MagicString__default(raw);
159
+ if (genDynamicFallback && chunk.isEntry) {
160
+ ms.prepend(forceDynamicImportUsage);
161
+ }
162
+ if (raw.includes(legacyEnvVarMarker)) {
163
+ const re = new RegExp(legacyEnvVarMarker, "g");
164
+ let match;
165
+ while (match = re.exec(raw)) {
166
+ ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
167
+ }
168
+ }
169
+ if (config.build.sourcemap) {
170
+ return {
171
+ code: ms.toString(),
172
+ map: ms.generateMap({ hires: true })
173
+ };
174
+ }
175
+ return {
176
+ code: ms.toString()
177
+ };
178
+ }
179
+ if (!genLegacy) {
180
+ return null;
181
+ }
182
+ opts.__vite_skip_esbuild__ = true;
183
+ opts.__vite_force_terser__ = true;
184
+ opts.__vite_skip_asset_emit__ = true;
185
+ const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
186
+ const sourceMaps = !!config.build.sourcemap;
187
+ const babel2 = await loadBabel();
188
+ const { code, map } = babel2.transform(raw, {
189
+ babelrc: false,
190
+ configFile: false,
191
+ compact: true,
192
+ sourceMaps,
193
+ inputSourceMap: sourceMaps ? chunk.map : void 0,
194
+ presets: [
195
+ [
196
+ () => ({
197
+ plugins: [
198
+ recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
199
+ replaceLegacyEnvBabelPlugin(),
200
+ wrapIIFEBabelPlugin()
201
+ ]
202
+ })
203
+ ],
204
+ [
205
+ "env",
206
+ {
207
+ targets,
208
+ modules: false,
209
+ bugfixes: true,
210
+ loose: false,
211
+ useBuiltIns: needPolyfills ? "usage" : false,
212
+ corejs: needPolyfills ? {
213
+ version: _require("core-js/package.json").version,
214
+ proposals: false
215
+ } : void 0,
216
+ shippedProposals: true,
217
+ ignoreBrowserslistConfig: options.ignoreBrowserslistConfig
218
+ }
219
+ ]
220
+ ]
221
+ });
222
+ if (code)
223
+ return { code, map };
224
+ return null;
225
+ },
226
+ transformIndexHtml(html, { chunk }) {
227
+ if (config.build.ssr)
228
+ return;
229
+ if (!chunk)
230
+ return;
231
+ if (chunk.fileName.includes("-legacy")) {
232
+ facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
233
+ return;
234
+ }
235
+ const tags = [];
236
+ const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
237
+ const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
238
+ if (modernPolyfillFilename) {
239
+ tags.push({
240
+ tag: "script",
241
+ attrs: {
242
+ type: "module",
243
+ src: `${config.base}${modernPolyfillFilename}`
244
+ }
245
+ });
246
+ } else if (modernPolyfills.size) {
247
+ throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
248
+ }
249
+ if (!genLegacy) {
250
+ return { html, tags };
251
+ }
252
+ tags.push({
253
+ tag: "script",
254
+ attrs: { nomodule: true },
255
+ children: safari10NoModuleFix,
256
+ injectTo: "body"
257
+ });
258
+ const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
259
+ if (legacyPolyfillFilename) {
260
+ tags.push({
261
+ tag: "script",
262
+ attrs: {
263
+ nomodule: true,
264
+ id: legacyPolyfillId,
265
+ src: `${config.base}${legacyPolyfillFilename}`
266
+ },
267
+ injectTo: "body"
268
+ });
269
+ } else if (legacyPolyfills.size) {
270
+ throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
271
+ }
272
+ const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
273
+ if (legacyEntryFilename) {
274
+ tags.push({
275
+ tag: "script",
276
+ attrs: {
277
+ nomodule: true,
278
+ id: legacyEntryId,
279
+ "data-src": config.base + legacyEntryFilename
280
+ },
281
+ children: systemJSInlineCode,
282
+ injectTo: "body"
283
+ });
284
+ } else {
285
+ throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
286
+ }
287
+ if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {
288
+ tags.push({
289
+ tag: "script",
290
+ attrs: { type: "module" },
291
+ children: detectModernBrowserCode,
292
+ injectTo: "head"
293
+ });
294
+ tags.push({
295
+ tag: "script",
296
+ attrs: { type: "module" },
297
+ children: dynamicFallbackInlineCode,
298
+ injectTo: "head"
299
+ });
300
+ }
301
+ return {
302
+ html,
303
+ tags
304
+ };
305
+ },
306
+ generateBundle(opts, bundle) {
307
+ if (config.build.ssr) {
308
+ return;
309
+ }
310
+ if (isLegacyBundle(bundle, opts)) {
311
+ for (const name in bundle) {
312
+ if (bundle[name].type === "asset") {
313
+ delete bundle[name];
314
+ }
315
+ }
316
+ }
317
+ }
318
+ };
319
+ let envInjectionFailed = false;
320
+ const legacyEnvPlugin = {
321
+ name: "vite:legacy-env",
322
+ config(config2, env) {
323
+ if (env) {
324
+ return {
325
+ define: {
326
+ "import.meta.env.LEGACY": env.command === "serve" || config2.build?.ssr ? false : legacyEnvVarMarker
327
+ }
328
+ };
329
+ } else {
330
+ envInjectionFailed = true;
331
+ }
332
+ },
333
+ configResolved(config2) {
334
+ if (envInjectionFailed) {
335
+ config2.logger.warn(`[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due to incompatible vite version (requires vite@^2.0.0-beta.69).`);
336
+ }
337
+ }
338
+ };
339
+ return [
340
+ legacyConfigPlugin,
341
+ legacyGenerateBundlePlugin,
342
+ legacyPostPlugin,
343
+ legacyEnvPlugin
344
+ ];
345
+ }
346
+ async function detectPolyfills(code, targets, list) {
347
+ const babel2 = await loadBabel();
348
+ const { ast } = babel2.transform(code, {
349
+ ast: true,
350
+ babelrc: false,
351
+ configFile: false,
352
+ presets: [
353
+ [
354
+ "env",
355
+ {
356
+ targets,
357
+ modules: false,
358
+ useBuiltIns: "usage",
359
+ corejs: { version: 3, proposals: false },
360
+ shippedProposals: true,
361
+ ignoreBrowserslistConfig: true
362
+ }
363
+ ]
364
+ ]
365
+ });
366
+ for (const node of ast.program.body) {
367
+ if (node.type === "ImportDeclaration") {
368
+ const source = node.source.value;
369
+ if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) {
370
+ list.add(source);
371
+ }
372
+ }
373
+ }
374
+ }
375
+ async function buildPolyfillChunk(name, imports, bundle, facadeToChunkMap, buildOptions, externalSystemJS) {
376
+ let { minify, assetsDir } = buildOptions;
377
+ minify = minify ? "terser" : false;
378
+ const res = await vite.build({
379
+ root: path__default.dirname(url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)))),
380
+ configFile: false,
381
+ logLevel: "error",
382
+ plugins: [polyfillsPlugin(imports, externalSystemJS)],
383
+ build: {
384
+ write: false,
385
+ target: false,
386
+ minify,
387
+ assetsDir,
388
+ rollupOptions: {
389
+ input: {
390
+ [name]: polyfillId
391
+ },
392
+ output: {
393
+ format: name.includes("legacy") ? "iife" : "es",
394
+ manualChunks: void 0
395
+ }
396
+ }
397
+ }
398
+ });
399
+ const _polyfillChunk = Array.isArray(res) ? res[0] : res;
400
+ if (!("output" in _polyfillChunk))
401
+ return;
402
+ const polyfillChunk = _polyfillChunk.output[0];
403
+ for (const key in bundle) {
404
+ const chunk = bundle[key];
405
+ if (chunk.type === "chunk" && chunk.facadeModuleId) {
406
+ facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
407
+ }
408
+ }
409
+ bundle[polyfillChunk.fileName] = polyfillChunk;
410
+ }
411
+ const polyfillId = "\0vite/legacy-polyfills";
412
+ function polyfillsPlugin(imports, externalSystemJS) {
413
+ return {
414
+ name: "vite:legacy-polyfills",
415
+ resolveId(id) {
416
+ if (id === polyfillId) {
417
+ return id;
418
+ }
419
+ },
420
+ load(id) {
421
+ if (id === polyfillId) {
422
+ return [...imports].map((i) => `import "${i}";`).join("") + (externalSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
423
+ }
424
+ }
425
+ };
426
+ }
427
+ function isLegacyChunk(chunk, options) {
428
+ return options.format === "system" && chunk.fileName.includes("-legacy");
429
+ }
430
+ function isLegacyBundle(bundle, options) {
431
+ if (options.format === "system") {
432
+ const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
433
+ return !!entryChunk && entryChunk.fileName.includes("-legacy");
434
+ }
435
+ return false;
436
+ }
437
+ function recordAndRemovePolyfillBabelPlugin(polyfills) {
438
+ return ({ types: t }) => ({
439
+ name: "vite-remove-polyfill-import",
440
+ post({ path: path2 }) {
441
+ path2.get("body").forEach((p) => {
442
+ if (t.isImportDeclaration(p)) {
443
+ polyfills.add(p.node.source.value);
444
+ p.remove();
445
+ }
446
+ });
447
+ }
448
+ });
449
+ }
450
+ function replaceLegacyEnvBabelPlugin() {
451
+ return ({ types: t }) => ({
452
+ name: "vite-replace-env-legacy",
453
+ visitor: {
454
+ Identifier(path2) {
455
+ if (path2.node.name === legacyEnvVarMarker) {
456
+ path2.replaceWith(t.booleanLiteral(true));
457
+ }
458
+ }
459
+ }
460
+ });
461
+ }
462
+ function wrapIIFEBabelPlugin() {
463
+ return ({ types: t, template }) => {
464
+ const buildIIFE = template(";(function(){%%body%%})();");
465
+ return {
466
+ name: "vite-wrap-iife",
467
+ post({ path: path2 }) {
468
+ if (!this.isWrapped) {
469
+ this.isWrapped = true;
470
+ path2.replaceWith(t.program(buildIIFE({ body: path2.node.body })));
471
+ }
472
+ }
473
+ };
474
+ };
475
+ }
476
+ const cspHashes = [
477
+ crypto.createHash("sha256").update(safari10NoModuleFix).digest("base64"),
478
+ crypto.createHash("sha256").update(systemJSInlineCode).digest("base64"),
479
+ crypto.createHash("sha256").update(detectModernBrowserCode).digest("base64"),
480
+ crypto.createHash("sha256").update(dynamicFallbackInlineCode).digest("base64")
481
+ ];
482
+
483
+ module.exports = viteLegacyPlugin;
484
+ module.exports.cspHashes = cspHashes;
485
+ module.exports["default"] = viteLegacyPlugin;
486
+ module.exports.detectPolyfills = detectPolyfills;
@@ -0,0 +1,37 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ interface Options {
4
+ /**
5
+ * default: 'defaults'
6
+ */
7
+ targets?: string | string[] | {
8
+ [key: string]: string;
9
+ };
10
+ /**
11
+ * default: false
12
+ */
13
+ ignoreBrowserslistConfig?: boolean;
14
+ /**
15
+ * default: true
16
+ */
17
+ polyfills?: boolean | string[];
18
+ additionalLegacyPolyfills?: string[];
19
+ /**
20
+ * default: false
21
+ */
22
+ modernPolyfills?: boolean | string[];
23
+ /**
24
+ * default: true
25
+ */
26
+ renderLegacyChunks?: boolean;
27
+ /**
28
+ * default: false
29
+ */
30
+ externalSystemJS?: boolean;
31
+ }
32
+
33
+ declare function viteLegacyPlugin(options?: Options): Plugin[];
34
+ declare function detectPolyfills(code: string, targets: any, list: Set<string>): Promise<void>;
35
+ declare const cspHashes: string[];
36
+
37
+ export { cspHashes, viteLegacyPlugin as default, detectPolyfills };