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

Import error in the browser and blank page in some templates (subst) #4302

Closed
6 tasks done
Mesteery opened this issue Jul 18, 2021 · 20 comments
Closed
6 tasks done

Import error in the browser and blank page in some templates (subst) #4302

Mesteery opened this issue Jul 18, 2021 · 20 comments

Comments

@Mesteery
Copy link
Contributor

Mesteery commented Jul 18, 2021

Describe the bug

When I scaffold a new Vue or Preact project with create-vite@631a9bf, and then run npm run dev (after installing the dependencies), I get the Uncaught SyntaxError: import not found: default in Firefox, and a blank page.

I can reproduce this with CJS and ESM (without and with TypeScript). But also with [email protected], except that you have to remember to add "type": "module" in the package.json, or transform the imports and exports in vite.config.js into CJS.
I can also reproduce this bug with Edge: Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=620176f5' does not provide an export named 'default' (same error).

I specify that the normal and TypeScript versions of React, Svelte templates work correctly.

Nevertheless, the problem seems to disappear, when the project is built: vite build && vite preview, the template works, there are no errors, and the page is not blank (for Vue & Preact).

Vue template (blank page & error)

image

Preact template (blank page & error)

(With preact() -> preact.default(), because it doesn't work without.)
image

Lit Element template (error)

image

Refs: #4293 (comment)

Reproduction

https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-vue
https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-vue-ts
https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-preact
https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-preact-ts
https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-lit-element
https://github.com/Mesteery/vite/tree/templates/enable-esm/packages/create-vite/template-lit-element-ts

System Info

System:
    OS: Windows 10 10.0.19043
    CPU: (4) x64 Intel(R) Core(TM) i5-2410M CPU @ 2.30GHz
    Memory: 4.13 GB / 7.94 GB
  Binaries:
    Node: 16.5.0 - ~\AppData\Local\Volta\tools\image\node\16.5.0\node.EXE
    Yarn: 1.22.10 - ~\AppData\Local\Volta\tools\image\yarn\1.22.10\bin\yarn.CMD
    npm: 7.19.1 - ~\AppData\Local\Volta\tools\image\node\16.5.0\npm.CMD
  Browsers:
    ~~Edge: Spartan (44.19041.1023.0), Chromium (91.0.864.67)~~
    Firefox Developer (91.0b3)
  npmPackages:
    @vitejs/plugin-vue: ^1.2.5 => 1.2.5
    vite: ^2.4.2 => 2.4.2

Used Package Manager

npm

Logs

With Vue template:

vite:config native esm config loaded in 304ms URL {
  href: 'file:///C:/Users/me/workspace/vite-experiments/vue/vite.config.js',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/C:/Users/me/workspace/vite-experiments/vue/vite.config.js',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
} +0ms
  vite:config using resolved config: {
  vite:config   plugins: [
  vite:config     'vite:pre-alias',
  vite:config     'alias',
  vite:config     'vite:dynamic-import-polyfill',
  vite:config     'vite:resolve',
  vite:config     'vite:html',
  vite:config     'vite:css',
  vite:config     'vite:esbuild',
  vite:config     'vite:json',
  vite:config     'vite:wasm',
  vite:config     'vite:worker',
  vite:config     'vite:asset',
  vite:config     'vite:vue',
  vite:config     'vite:define',
  vite:config     'vite:css-post',
  vite:config     'vite:client-inject',
  vite:config     'vite:import-analysis'
  vite:config   ],
  vite:config   server: { fs: { strict: undefined, allow: [Array] } },
  vite:config   define: { __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: false },
  vite:config   ssr: { external: [ 'vue', '@vue/server-renderer' ] },
  vite:config   configFile: 'C:/Users/me/workspace/vite-experiments/vue/vite.config.js',
  vite:config   configFileDependencies: [],
  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     server: { fs: [Object] }
  vite:config   },
  vite:config   root: 'C:/Users/me/workspace/vite-experiments/vue',
  vite:config   base: '/',
  vite:config   resolve: { dedupe: undefined, alias: [ [Object] ] },
  vite:config   publicDir: 'C:\\Users\\me\\workspace\\vite-experiments\\vue\\public',
  vite:config   cacheDir: 'C:\\Users\\me\\workspace\\vite-experiments\\vue\\node_modules\\.vite',
  vite:config   command: 'serve',
  vite:config   mode: 'development',
  vite:config   isProduction: false,
  vite:config   build: {
  vite:config     target: [ 'es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1' ],
  vite:config     polyfillDynamicImport: false,
  vite:config     outDir: 'dist',
  vite:config     assetsDir: 'assets',
  vite:config     assetsInlineLimit: 4096,
  vite:config     cssCodeSplit: true,
  vite:config     sourcemap: false,
  vite:config     rollupOptions: {},
  vite:config     commonjsOptions: { include: [Array], extensions: [Array] },
  vite:config     dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] },
  vite:config     minify: 'terser',
  vite:config     terserOptions: {},
  vite:config     cleanCssOptions: {},
  vite:config     write: true,
  vite:config     emptyOutDir: null,
  vite:config     manifest: false,
  vite:config     lib: false,
  vite:config     ssr: false,
  vite:config     ssrManifest: false,
  vite:config     brotliSize: true,
  vite:config     chunkSizeWarningLimit: 500,
  vite:config     watch: null
  vite:config   },
  vite:config   env: { BASE_URL: '/', MODE: 'development', DEV: true, PROD: false },
  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   },
  vite:config   createResolver: [Function: createResolver],
  vite:config   optimizeDeps: { esbuildOptions: { keepNames: undefined } }
  vite:config } +19ms
  vite:deps Hash is consistent. Skipping. Use --force to override. +0ms

  vite v2.4.2 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 753ms.

  vite:time 2ms   / +0ms
  vite:spa-fallback Rewriting GET / to /index.html +0ms
  vite:time 37ms  /index.html +110ms
  vite:resolve 5ms   /Users/Original ME/workspace/vite-experiments/vue/node_modules/vite/dist/client/client -> C:/Users/Original ME/workspace/vite-experiments/vue/node_modules/vite/dist/client/client.mjs +0ms
  vite:resolve 8ms   /@vite/client -> C:/Users/Original ME/workspace/vite-experiments/vue/node_modules/vite/dist/client/client.mjs +1ms
  vite:resolve 2ms   /src/main.js -> C:/Users/me/workspace/vite-experiments/vue/src/main.js +18ms
  vite:load 12ms  [fs] /@vite/client +0ms
  vite:resolve 2ms   ./env -> C:/Users/Original ME/workspace/vite-experiments/vue/node_modules/vite/dist/client/env.mjs +37ms
  vite:transform 27ms  /@vite/client +0ms
  vite:time 73ms  /@vite/client +146ms
  vite:load 42ms  [fs] /src/main.js +41ms
  vite:resolve 0ms   vue -> C:/Users/me/workspace/vite-experiments/vue/node_modules/.vite/vue.js?v=756ed77f&es-interop +16ms
  vite:resolve 1ms   /node_modules/.vite/vue.js?v=756ed77f&es-interop -> C:/Users/me/workspace/vite-experiments/vue/node_modules/.vite/vue.js?v=756ed77f&es-interop +3ms
  vite:resolve 1ms   ./App.vue -> C:/Users/me/workspace/vite-experiments/vue/src/App.vue +20ms
  vite:resolve 1ms   /src/App.vue -> C:/Users/me/workspace/vite-experiments/vue/src/App.vue +1ms
  vite:resolve 0ms   /node_modules/.vite/vue.js?v=756ed77f -> C:/Users/me/workspace/vite-experiments/vue/node_modules/.vite/vue.js?v=756ed77f +1ms
  vite:transform 32ms  /src/main.js +36ms
  vite:time 82ms  /src/main.js +35ms
  vite:load 3ms   [fs] ..\..\..\..\Original ME\workspace\vite-experiments\vue\node_modules\vite\dist\client\env.mjs +48ms
  vite:rewrite 0ms   [no imports] C:/Users/Original ME/workspace/vite-experiments/vue/node_modules/vite/dist/client/env.mjs +0ms
  vite:transform 2ms   ..\..\..\..\Original ME\workspace\vite-experiments\vue\node_modules\vite\dist\client\env.mjs +19ms
  vite:time 16ms  ..\..\..\..\Original ME\workspace\vite-experiments\vue\node_modules\vite\dist\client\env.mjs +23ms
  vite:load 7ms   [fs] /node_modules/.vite/vue.js?v=756ed77f +34ms
  vite:rewrite 5ms   [no imports] node_modules\.vite\vue.js?v=756ed77f +50ms
  vite:transform 6ms   /node_modules/.vite/vue.js?v=756ed77f +49ms
  vite:time 38ms  /node_modules/.vite/vue.js?v=756ed77f +47ms
  vite:load 27ms  [fs] /src/App.vue +24ms
[@vue/compiler-sfc] <script setup> is still an experimental proposal.
Follow its status at https://github.com/vuejs/rfcs/pull/227.

[@vue/compiler-sfc] When using experimental features,
it is recommended to pin your vue dependencies to exact versions to avoid breakage.

  vite:resolve 1ms   ./components/HelloWorld.vue -> C:/Users/me/workspace/vite-experiments/vue/src/components/HelloWorld.vue +168ms
  vite:resolve 1ms   /src/components/HelloWorld.vue -> C:/Users/me/workspace/vite-experiments/vue/src/components/HelloWorld.vue +1ms
  vite:resolve 1ms   /src/App.vue?vue&type=style&index=0&lang.css -> C:/Users/me/workspace/vite-experiments/vue/src/App.vue?vue&type=style&index=0&lang.css +7ms
  vite:hmr [self-accepts] src\App.vue +0ms
  vite:transform 102ms /src/App.vue +110ms
  vite:time 136ms /src/App.vue +108ms
  vite:load 0ms   [plugin] /src/App.vue?vue&type=style&index=0&lang.css +145ms
  vite:load 14ms  [fs] /src/components/HelloWorld.vue +11ms
[@vue/compiler-sfc] `defineProps` is a compiler macro and no longer needs to be imported.

  vite:resolve 1ms   /src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css -> C:/Users/me/workspace/vite-experiments/vue/src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css +133ms
  vite:hmr [self-accepts] src\components\HelloWorld.vue +132ms
  vite:transform 81ms  /src/components/HelloWorld.vue +132ms
  vite:time 101ms /src/components/HelloWorld.vue +132ms
  vite:hmr [self-accepts] src\App.vue?vue&type=style&index=0&lang.css +37ms
  vite:transform 127ms /src/App.vue?vue&type=style&index=0&lang.css +35ms
  vite:time 131ms /src/App.vue?vue&type=style&index=0&lang.css +35ms
  vite:load 0ms   [plugin] /src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css +123ms
  vite:hmr [self-accepts] src\components\HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css +22ms
  vite:transform 15ms  /src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css +23ms
  vite:time 21ms  /src/components/HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css +23ms

Validations

Edit: sorry for all the edits, but GitHub strangely removes some changes on a new edit (cf. edit history).

I take the opportunity to ask a question: is it normal that vite build in the Lit Element template, generates only dist/X.es.js?

@haoqunjiang
Copy link
Member

Can't reproduce. What's the actual project like?

@Mesteery
Copy link
Contributor Author

Mesteery commented Jul 18, 2021

@haoqunjiang
Copy link
Member

I don't think so. I can't reproduce this error with the Vue template.
Please check the error trace in your browser.

Here's what I got from Chrome:
image

There's no default import in the HelloWorld.vue component. No way it throws such an error.

@Mesteery
Copy link
Contributor Author

I have this in HelloWorld.vue:

import { createHotContext as __vite__createHotContext } from "/@vite/client";import.meta.hot = __vite__createHotContext("/src/components/HelloWorld.vue");import __vite__cjsImport0_vue from "/node_modules/.vite/vue.js?v=37506fec"; const reactive = __vite__cjsImport0_vue["reactive"]


const _sfc_main = {
  props: {
  msg: String
},
  setup(__props, { expose }) {
  expose()



const state = reactive({ count: 0 })

const __returned__ = { state, reactive }
Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
return __returned__
}

}
import __vite__cjsImport1_vue from "/node_modules/.vite/vue.js?v=37506fec"; const _toDisplayString = __vite__cjsImport1_vue["toDisplayString"]; const _createVNode = __vite__cjsImport1_vue["createVNode"]; const _createTextVNode = __vite__cjsImport1_vue["createTextVNode"]; const _Fragment = __vite__cjsImport1_vue["Fragment"]; const _openBlock = __vite__cjsImport1_vue["openBlock"]; const _createBlock = __vite__cjsImport1_vue["createBlock"]; const _withScopeId = __vite__cjsImport1_vue["withScopeId"]; const _pushScopeId = __vite__cjsImport1_vue["pushScopeId"]; const _popScopeId = __vite__cjsImport1_vue["popScopeId"]
const _withId = /*#__PURE__*/_withScopeId("data-v-469af010")

_pushScopeId("data-v-469af010")

@haoqunjiang
Copy link
Member

Okay. I'll check it in Windows tomorrow.
So in your ./node_modules/.vite/_metadata.json, there must be an optimized.vue.needsInterop field that is set to true, which is wrong.

The logic is in

function needsInterop(
id: string,
exportsData: ExportsData,
outputs: Record<string, any>,
cacheDirOutputPath: string
): boolean {
if (KNOWN_INTEROP_IDS.has(id)) {
return true
}
const [imports, exports] = exportsData
// entry has no ESM syntax - likely CJS or UMD
if (!exports.length && !imports.length) {
return true
}
// if a peer dependency used require() on a ESM dependency, esbuild turns the
// ESM dependency's entry chunk into a single default export... detect
// such cases by checking exports mismatch, and force interop.
const flatId = flattenId(id) + '.js'
let generatedExports: string[] | undefined
for (const output in outputs) {
if (
normalizePath(output) ===
normalizePath(path.join(cacheDirOutputPath, flatId))
) {
generatedExports = outputs[output].exports
break
}
}
if (
!generatedExports ||
(isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))
) {
return true
}
return false
}

I don't see anything wrong and can't reproduce the issue in macOS. So I'll check later in Windows.

@haoqunjiang
Copy link
Member

And please, I need the generated project with lockfiles.

Mesteery added a commit to Mesteery/vite that referenced this issue Jul 18, 2021
@Mesteery
Copy link
Contributor Author

normalizePath(output) ===

The error was caused by output which was relative to something (../../../me/workspace/vite-experiments/vue/node_modules/.vite/vue.js).

@haoqunjiang
Copy link
Member

But how does that happen? Why isn't the output path the same as the actual cache path?

@Mesteery
Copy link
Contributor Author

I don't know, it's from ESBuild.

@haoqunjiang
Copy link
Member

I still can't reproduce this issue. So please provide a full reproduction.
If it's caused by initiating projects inside a monorepo, please provide the monorepo as a reproduction. Otherwise I can't validate your fix.

@Mesteery
Copy link
Contributor Author

Mesteery commented Jul 19, 2021

As I said above, I did nothing more than use the template above. I just did

npm init vite vue -t vue
cd vue
npm install
# add "type": "module" in package.json, then
npm run dev

@haoqunjiang
Copy link
Member

../../../me/workspace/vite-experiments/vue/node_modules/.vite/vue.js is obviously not the same as C:/Users/me/workspace/vite-experiments/2/. Are there 2 different projects and you are using npm link, or are they inside the same workspace that dependencies are hoisted?

@Mesteery
Copy link
Contributor Author

(For the 2 vs vue, i renamed the folder yesterday.)

Are there 2 different projects and you are using npm link, or are they inside the same workspace that dependencies are hoisted?

2 and vue are the same project. I didn't use npm link.

@Mesteery
Copy link
Contributor Author

Besides, I don't know if it changes. But C:\Users\me is a symbolic link of C:\Users\Original ME (for example). Should I update the logs (because I replaced Original ME by me)?

@haoqunjiang
Copy link
Member

Yes. And I think that's the problem. esbuild follows the symbolic link and returns the weird relative path string.

@Mesteery
Copy link
Contributor Author

Mesteery commented Jul 19, 2021

Reproduction

(CMD)

:: go to a folder that has no symlinked parents
mkdir something
:: the name is not important
mklink /j something-junction something

cd something
npm init -y vite vite-project -- -t vue
::                                  ^ or preact or lit element template

cd vite-project
npm install
:: this should work without errors
npm run dev

cd ..\..
cd something-junction\vite-project
:: observe error
npm run dev

The first error is (#4293):

failed to load config from D:\dev\jonction\vite-project\vite.config.js
error when starting dev server:
D:\dev\basedir\vite-project\vite.config.js:1
import { defineConfig } from 'vite'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1025:15)
    at Module._compile (node:internal/modules/cjs/loader:1059:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
    at Object.require.extensions.<computed> [as .js] (D:\dev\basedir\vite-project\node_modules\vite\dist\node\chunks\dep-11db14da.js:75452:13)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at loadConfigFromBundledFile (D:\dev\basedir\vite-project\node_modules\vite\dist\node\chunks\dep-11db14da.js:75457:17)

(jonction is a junction of basedir).

You can fix this by adding "type": "module" to the package.json. It work, but as described above, there is the "default" import error in the browser and a blank page (or almost blank for lit element)

This is also reproducible when you scaffold the project directly in the junction (start in something-junction instead of something).

@Shinigami92
Copy link
Member

This is currently a so specific use case that I think you should manually add it after the initialization of the project

I would currently vote for closing this PR
@sodatea please decide and answer or close this PR

@Mesteery
Copy link
Contributor Author

Mesteery commented Jul 19, 2021

I agree, but this (enabling ESM manually) is obviously not the solution (as shown above, it is not enough).

@TTSKarlsson
Copy link

I encountered this problem today too in a folder junction pointing from J:\dev\js\sec to H:\dev\js\sec.

It works when running the dev server / building from terminal when in H:, but not when in the junction folder on J:.

Other apps are sensitive to their launch parameters paths (vscode for example) so it would be nice if vite worked together with vscode in these circumstances. Symbolic links are not that uncommon after all.

@sapphi-red sapphi-red changed the title Import error in the browser and blank page in some templates Import error in the browser and blank page in some templates (subst) Dec 8, 2022
@bluwy
Copy link
Member

bluwy commented Dec 29, 2022

Closing this in favour of #10802 which existing Windows linking issues are directed to.

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

Successfully merging a pull request may close this issue.

5 participants