Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@vitejs/plugin-legacy breaks code: Failed to resolve import "_" from "dist/main.js". Does the file exist? #17471

Closed
7 tasks done
EverStarck opened this issue Jun 13, 2024 · 2 comments

Comments

@EverStarck
Copy link

Describe the bug

This only happens when using legacy plugin.

I'm trying to build static js files to import them in differents sites. When I try to load the dist files, I get an error:

[vite] Internal server error: Failed to resolve import "_" from "dist/main.js". Does the file exist?
  Plugin: vite:import-analysis
  File: /home/projects/vitejs-vite-dkxyof/dist/main.js:1:37
  1  |  function c(){import.meta.url,import("_").catch(()=>1),async function*(){}().next()}function r(e){let t=0;const o=n=>{t=n,e.innerHTML="count is ".concat(t)};e.addEventListener("click",()=>o(t+1)),o(0)}document.querySelector("#app").innerHTML='\n  <div>\n    <a href="https://vitejs.dev" target="_blank">\n    </a>\n    <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank">\n    </a>\n    <h1>Hello Vite!</h1>\n    <div class="card">\n      <button id="counter" type="button"></button>\n    </div>\n    <p class="read-the-docs">\n      Click on the Vite logo to learn more\n    </p>\n  </div>\n';r(document.querySelector("#counter"));console.log("im gonna kms");export{c as __vite_legacy_guard};
     |                                      ^
  2  |  
      at _formatError (file:///home/projects/vitejs-vite-dkxyof/node_modules/vite/dist/node/chunks/dep-h78lQ5BT.js:49752:41)
      at error (file:///home/projects/vitejs-vite-dkxyof/node_modules/vite/dist/node/chunks/dep-h78lQ5BT.js:49747:16)
      at normalizeUrl (file:///home/projects/vitejs-vite-dkxyof/node_modules/vite/dist/node/chunks/dep-h78lQ5BT.js:64309:23)
```the 

### Reproduction

https://stackblitz.com/edit/vitejs-vite-dkxyof?file=preview%2Findex-preview.html

### Steps to reproduce

Run `npm i` and then `npm run dev`. Go to `/index-preview.html` (this file has the build script. `index.html` has a `.ts` script).

Check the console.

### System Info

```shell
System:
    OS: macOS 13.2
    CPU: (10) arm64 Apple M1 Pro
    Memory: 85.36 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node
    npm: 10.2.4 - ~/.nvm/versions/node/v20.11.1/bin/npm
    bun: 1.0.0 - ~/.bun/bin/bun
  Browsers:
    Chrome: 124.0.6367.62
    Edge: 119.0.2151.97
    Safari: 16.3
  npmPackages:
    @vitejs/plugin-legacy: 5.4.1 => 5.4.1 
    vite: ^5.2.11 => 5.3.0

Used Package Manager

npm

Logs

Click to expand!
❯ npm run build -- --debug

> [email protected] build
> VITE_NODE_ENV=production vite build --debug

  vite:config bundled config file loaded in 286.36ms +0ms
[@vitejs/plugin-legacy] modernTargets: edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12
[@vitejs/plugin-legacy] targets: chrome >= 60, Safari >= 10.1, iOS >= 10.3, Firefox >= 54, Edge >= 16
  vite:config using resolved config: {
  vite:config   plugins: [
  vite:config     'vite:build-metadata',
  vite:config     'vite:watch-package-data',
  vite:config     'vite:pre-alias',
  vite:config     'alias',
  vite:config     'vite:modulepreload-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html-inline-proxy',
  vite:config     'vite:css',
  vite:config     'vite:esbuild',
  vite:config     'vite:json',
  vite:config     'vite:wasm-helper',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite:legacy-config',
  vite:config     'vite:legacy-generate-polyfill-chunk',
  vite:config     'vite:wasm-fallback',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:build-html',
  vite:config     'vite:worker-import-meta-url',
  vite:config     'vite:asset-import-meta-url',
  vite:config     'vite:force-systemjs-wrap-complete',
  vite:config     'commonjs',
  vite:config     'vite:data-uri',
  vite:config     'vite:dynamic-import-vars',
  vite:config     'vite:import-glob',
  vite:config     'vite:legacy-post-process',
  vite:config     'vite:build-import-analysis',
  vite:config     'vite:esbuild-transpile',
  vite:config     'vite:terser',
  vite:config     'vite:reporter',
  vite:config     'vite:load-fallback'
  vite:config   ],
  vite:config   build: {
  vite:config     target: [ 'es2020', 'edge79', 'firefox67', 'chrome64', 'safari12' ],
  vite:config     cssTarget: 'chrome61',
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: true,
  vite:config     sourcemap: false,
  vite:config     rollupOptions: { input: [Object], output: [Array] },
  vite:config     minify: 'esbuild',
  vite:config     terserOptions: {},
  vite:config     write: true,
  vite:config     emptyOutDir: null,
  vite:config     copyPublicDir: true,
  vite:config     manifest: false,
  vite:config     lib: false,
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     ssrEmitAssets: false,
  vite:config     reportCompressedSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null,
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] },
  vite:config     modulePreload: { polyfill: true },
  vite:config     cssMinify: true
  vite:config   },
  vite:config   define: { 'import.meta.env.LEGACY': '__VITE_IS_LEGACY__' },
  vite:config   configFile: '/home/projects/vitejs-vite-dkxyof/vite.config.ts',
  vite:config   configFileDependencies: [ '/home/projects/vitejs-vite-dkxyof/vite.config.ts' ],
  vite:config   inlineConfig: {
  vite:config     root: undefined,
  vite:config     base: undefined,
  vite:config     mode: undefined,
  vite:config     configFile: undefined,
  vite:config     logLevel: undefined,
  vite:config     clearScreen: undefined,
  vite:config     build: {}
  vite:config   },
  vite:config   root: '/home/projects/vitejs-vite-dkxyof',
  vite:config   base: '/',
  vite:config   rawBase: '/',
  vite:config   resolve: {
  vite:config     mainFields: [ 'browser', 'module', 'jsnext:main', 'jsnext' ],
  vite:config     conditions: [],
  vite:config     extensions: [
  vite:config       '.mjs',  '.js',
  vite:config       '.mts',  '.ts',
  vite:config       '.jsx',  '.tsx',
  vite:config       '.json'
  vite:config     ],
  vite:config     dedupe: [],
  vite:config     preserveSymlinks: false,
  vite:config     alias: [ [Object], [Object] ]
  vite:config   },
  vite:config   publicDir: '/home/projects/vitejs-vite-dkxyof/public',
  vite:config   cacheDir: '/home/projects/vitejs-vite-dkxyof/node_modules/.vite',
  vite:config   command: 'build',
  vite:config   mode: 'production',
  vite:config   ssr: {
  vite:config     target: 'node',
  vite:config     optimizeDeps: { noDiscovery: true, esbuildOptions: [Object] }
  vite:config   },
  vite:config   isWorker: false,
  vite:config   mainConfig: null,
  vite:config   bundleChain: [],
  vite:config   isProduction: true,
  vite:config   css: { lightningcss: undefined },
  vite:config   esbuild: { jsxDev: false },
  vite:config   server: {
  vite:config     preTransformRequests: true,
  vite:config     sourcemapIgnoreList: [Function: isInNodeModules$1],
  vite:config     middlewareMode: false,
  vite:config     fs: {
  vite:config       strict: true,
  vite:config       allow: [Array],
  vite:config       deny: [Array],
  vite:config       cachedChecks: undefined
  vite:config     }
  vite:config   },
  vite:config   preview: {
  vite:config     port: undefined,
  vite:config     strictPort: undefined,
  vite:config     host: undefined,
  vite:config     https: undefined,
  vite:config     open: undefined,
  vite:config     proxy: undefined,
  vite:config     cors: undefined,
  vite:config     headers: undefined
  vite:config   },
  vite:config   envDir: '/home/projects/vitejs-vite-dkxyof',
  vite:config   env: {
  vite:config     VITE_NODE_ENV: 'production',
  vite:config     BASE_URL: '/',
  vite:config     MODE: 'production',
  vite:config     DEV: false,
  vite:config     PROD: true
  vite:config   },
  vite:config   assetsInclude: [Function: assetsInclude],
  vite:config   logger: {
  vite:config     hasWarned: false,
  vite:config     info: [Function: info],
  vite:config     warn: [Function: warn],
  vite:config     warnOnce: [Function: warnOnce],
  vite:config     error: [Function: error],
  vite:config     clearScreen: [Function: clearScreen],
  vite:config     hasErrorLogged: [Function: hasErrorLogged]
  vite:config   },
  vite:config   packageCache: Map(1) {
  vite:config     'fnpd_/home/projects/vitejs-vite-dkxyof' => {
  vite:config       dir: '/home/projects/vitejs-vite-dkxyof',
  vite:config       data: [Object],
  vite:config       hasSideEffects: [Function: hasSideEffects],
  vite:config       webResolvedImports: {},
  vite:config       nodeResolvedImports: {},
  vite:config       setResolvedCache: [Function: setResolvedCache],
  vite:config       getResolvedCache: [Function: getResolvedCache]
  vite:config     },
  vite:config     set: [Function (anonymous)]
  vite:config   },
  vite:config   createResolver: [Function: createResolver],
  vite:config   optimizeDeps: {
  vite:config     holdUntilCrawlEnd: true,
  vite:config     esbuildOptions: { preserveSymlinks: false }
  vite:config   },
  vite:config   worker: { format: 'iife', plugins: '() => plugins', rollupOptions: {} },
  vite:config   appType: 'spa',
  vite:config   experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false },
  vite:config   getSortedPlugins: [Function: getSortedPlugins],
  vite:config   getSortedPluginHooks: [Function: getSortedPluginHooks]
  vite:config } +2ms
vite v5.3.0 building for production...
✓ 2 modules transformed.
rendering chunks (1)...[@vitejs/plugin-legacy] legacy polyfills: Set(3) {
  'core-js/modules/es.array.iterator.js',
  'core-js/modules/es.promise.js',
  'core-js/modules/web.dom-collections.iterator.js'
}
  vite:config using resolved config: {
  vite:config   mode: 'production',
  vite:config   root: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/dist',
  vite:config   configFile: undefined,
  vite:config   logLevel: 'error',
  vite:config   plugins: [
  vite:config     'vite:build-metadata',
  vite:config     'vite:watch-package-data',
  vite:config     'vite:pre-alias',
  vite:config     'alias',
  vite:config     'vite:modulepreload-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html-inline-proxy',
  vite:config     'vite:css',
  vite:config     'vite:json',
  vite:config     'vite:wasm-helper',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite:legacy-polyfills',
  vite:config     'vite:wasm-fallback',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:build-html',
  vite:config     'vite:worker-import-meta-url',
  vite:config     'vite:asset-import-meta-url',
  vite:config     'vite:force-systemjs-wrap-complete',
  vite:config     'commonjs',
  vite:config     'vite:data-uri',
  vite:config     'vite:dynamic-import-vars',
  vite:config     'vite:import-glob',
  vite:config     'vite:build-import-analysis',
  vite:config     'vite:terser',
  vite:config     'vite:reporter',
  vite:config     'vite:load-fallback'
  vite:config   ],
  vite:config   build: {
  vite:config     target: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
  vite:config     cssTarget: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: true,
  vite:config     sourcemap: false,
  vite:config     rollupOptions: { input: [Object], output: [Object] },
  vite:config     minify: 'terser',
  vite:config     terserOptions: {},
  vite:config     write: false,
  vite:config     emptyOutDir: null,
  vite:config     copyPublicDir: true,
  vite:config     manifest: false,
  vite:config     lib: false,
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     ssrEmitAssets: false,
  vite:config     reportCompressedSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null,
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] },
  vite:config     modulePreload: { polyfill: true },
  vite:config     cssMinify: true
  vite:config   },
  vite:config   esbuild: false,
  vite:config   optimizeDeps: {
  vite:config     holdUntilCrawlEnd: true,
  vite:config     esbuildOptions: { preserveSymlinks: false, target: 'es5' }
  vite:config   },
  vite:config   configFileDependencies: [],
  vite:config   inlineConfig: {
  vite:config     mode: 'production',
  vite:config     root: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/dist',
  vite:config     configFile: false,
  vite:config     logLevel: 'error',
  vite:config     plugins: [ [Object] ],
  vite:config     build: {
  vite:config       write: false,
  vite:config       minify: 'terser',
  vite:config       assetsDir: 'assets',
  vite:config       rollupOptions: [Object]
  vite:config     },
  vite:config     esbuild: false,
  vite:config     optimizeDeps: { esbuildOptions: [Object] }
  vite:config   },
  vite:config   base: '/',
  vite:config   rawBase: '/',
  vite:config   resolve: {
  vite:config     mainFields: [ 'browser', 'module', 'jsnext:main', 'jsnext' ],
  vite:config     conditions: [],
  vite:config     extensions: [
  vite:config       '.mjs',  '.js',
  vite:config       '.mts',  '.ts',
  vite:config       '.jsx',  '.tsx',
  vite:config       '.json'
  vite:config     ],
  vite:config     dedupe: [],
  vite:config     preserveSymlinks: false,
  vite:config     alias: [ [Object], [Object] ]
  vite:config   },
  vite:config   publicDir: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/dist/public',
  vite:config   cacheDir: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/node_modules/.vite',
  vite:config   command: 'build',
  vite:config   ssr: {
  vite:config     target: 'node',
  vite:config     optimizeDeps: { noDiscovery: true, esbuildOptions: [Object] }
  vite:config   },
  vite:config   isWorker: false,
  vite:config   mainConfig: null,
  vite:config   bundleChain: [],
  vite:config   isProduction: true,
  vite:config   css: { lightningcss: undefined },
  vite:config   server: {
  vite:config     preTransformRequests: true,
  vite:config     sourcemapIgnoreList: [Function: isInNodeModules$1],
  vite:config     middlewareMode: false,
  vite:config     fs: {
  vite:config       strict: true,
  vite:config       allow: [Array],
  vite:config       deny: [Array],
  vite:config       cachedChecks: undefined
  vite:config     }
  vite:config   },
  vite:config   preview: {
  vite:config     port: undefined,
  vite:config     strictPort: undefined,
  vite:config     host: undefined,
  vite:config     https: undefined,
  vite:config     open: undefined,
  vite:config     proxy: undefined,
  vite:config     cors: undefined,
  vite:config     headers: undefined
  vite:config   },
  vite:config   envDir: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/dist',
  vite:config   env: {
  vite:config     VITE_NODE_ENV: 'production',
  vite:config     BASE_URL: '/',
  vite:config     MODE: 'production',
  vite:config     DEV: false,
  vite:config     PROD: true
  vite:config   },
  vite:config   assetsInclude: [Function: assetsInclude],
  vite:config   logger: {
  vite:config     hasWarned: false,
  vite:config     info: [Function: info],
  vite:config     warn: [Function: warn],
  vite:config     warnOnce: [Function: warnOnce],
  vite:config     error: [Function: error],
  vite:config     clearScreen: [Function: clearScreen],
  vite:config     hasErrorLogged: [Function: hasErrorLogged]
  vite:config   },
  vite:config   packageCache: Map(2) {
  vite:config     'fnpd_/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy' => {
  vite:config       dir: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy',
  vite:config       data: [Object],
  vite:config       hasSideEffects: [Function: hasSideEffects],
  vite:config       webResolvedImports: {},
  vite:config       nodeResolvedImports: {},
  vite:config       setResolvedCache: [Function: setResolvedCache],
  vite:config       getResolvedCache: [Function: getResolvedCache]
  vite:config     },
  vite:config     'fnpd_/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy/dist' => {
  vite:config       dir: '/home/projects/vitejs-vite-dkxyof/node_modules/@vitejs/plugin-legacy',
  vite:config       data: [Object],
  vite:config       hasSideEffects: [Function: hasSideEffects],
  vite:config       webResolvedImports: {},
  vite:config       nodeResolvedImports: {},
  vite:config       setResolvedCache: [Function: setResolvedCache],
  vite:config       getResolvedCache: [Function: getResolvedCache]
  vite:config     },
  vite:config     set: [Function (anonymous)]
  vite:config   },
  vite:config   createResolver: [Function: createResolver],
  vite:config   worker: { format: 'iife', plugins: '() => plugins', rollupOptions: {} },
  vite:config   appType: 'spa',
  vite:config   experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false },
  vite:config   getSortedPlugins: [Function: getSortedPlugins],
  vite:config   getSortedPluginHooks: [Function: getSortedPluginHooks]
  vite:config } +906ms
dist/main-legacy.js        0.68 kB │ gzip:  0.42 kB
dist/polyfills-legacy.js  33.97 kB │ gzip: 13.94 kB
dist/main.js  0.72 kB │ gzip: 0.44 kB
✓ built in 1.49s

Validations

Copy link

stackblitz bot commented Jun 13, 2024

Fix this issue in StackBlitz Codeflow Start a new pull request in StackBlitz Codeflow.

@bluwy
Copy link
Member

bluwy commented Jun 17, 2024

After building, you can't use the built output files in the dev server again generally. Particularly in this case, Vite will inject guard code, like the import("_") so that it can decide in runtime whether to use the modern chunks or polyfill chunks.

If you want to use the built output files, you can use vite preview instead, which is a simple static file server that doesn't do additional path resolving like the error shown.

Altogether, if you're trying to get legacy support to work, it may still not be enough. Vite needs to inject additional scripts to handle when modern/legacy chunks are used. Here's an example html output you can replicate with a simple Vite project that has a root index.html.

<script type="module">import.meta.url;import("_").catch(()=>1);(async function*(){})().next();if(location.protocol!="file:"){window.__vite_is_modern_browser=true}</script>
<script type="module">!function(){if(window.__vite_is_modern_browser)return;console.warn("vite: loading legacy chunks, syntax error above and the same error below should be ignored");var e=document.getElementById("vite-legacy-polyfill"),n=document.createElement("script");n.src=e.src,n.onload=function(){System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))},document.body.appendChild(n)}();</script>
<script type="module" crossorigin src="./assets/polyfills-skbuN6Et.js"></script>
<script type="module" crossorigin src="./assets/index-DDYQejV-.js"></script>
<link rel="modulepreload" crossorigin href="./assets/chunk-main.DzdicFi7.js">
<body>...trimmed...</body>

<script nomodule>!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()}}();</script>
<script nomodule crossorigin id="vite-legacy-polyfill" src="./assets/polyfills-legacy-Cb2nEpmd.js"></script>
<script nomodule crossorigin id="vite-legacy-entry" data-src="./assets/index-legacy-D-CtGtjI.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>

You could replicate its flow manually if you like, but it may be tricky and out of scope of the plugin. Closing this as the rest are working as expected.

@bluwy bluwy closed this as not planned Won't fix, can't repro, duplicate, stale Jun 17, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Jul 2, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants