framework icon indicating copy to clipboard operation
framework copied to clipboard

Dynamic glob imports does not work with vite

Open pi0 opened this issue 2 years ago • 18 comments

Environment


  • Operating System: Linux
  • Node Version: v14.16.0
  • Nuxt Version: 3.0.0-27265876.3cd4494
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Describe the bug

Unpredictable dynamic imports like import(~/data/${name}json)` does not work with vite (dev-bundler)

Reproduction

https://stackblitz.com/edit/github-obezmd?file=app.vue

Additional context

As a workaround, one can use webpack using vite: false in nuxt.config.

Missing implementation is here but we probably need more to fix this.

Logs

Cannot read properties of undefined (reading 'stubModule')
at __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:1771:11)
at __ssrLoadModule__ (file://./.nuxt/dist/server/server.mjs:1762:25)
at ssrImport (file://./.nuxt/dist/server/server.mjs:1787:13)
at ssrDynamicImport (file://./.nuxt/dist/server/server.mjs:1798:12)
at eval (file://./.nuxt/dist/server/server.mjs:1678:70)
at Module.withAsyncContext (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7295:21)
at setup (file://./.nuxt/dist/server/server.mjs:1678:47)
at _sfc_main.setup (file://./.nuxt/dist/server/server.mjs:1708:23)
at callWithErrorHandling (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6615:22)
at setupStatefulComponent (./node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6241:29)

pi0 avatar Nov 04 '21 12:11 pi0

Is there is any update on this issue because i have the same problem

AbrahemAlhofe avatar Dec 06 '21 21:12 AbrahemAlhofe

@AbrahemAlhofe Unfortunately not yet. We would probably need a better vite dev SSR implementation (with on-demand bundling server) to make this possible.

pi0 avatar Dec 10 '21 11:12 pi0

Do we have an existing workaround? Or is putting images in public the only way to go?

Blakeinstein avatar Jan 27 '22 08:01 Blakeinstein

I would also be interested in a work around !

lacorde avatar Jan 28 '22 08:01 lacorde

I would also be interested in a work around !

Current workaround is to use webpack as the bundler instead of vite.

in your nuxt.config.ts set

export default defineNuxtConfig({
  ...
  vite: false,
  ...
})

Blakeinstein avatar Jan 28 '22 14:01 Blakeinstein

can not use unocss with vite: false

vite: false,
build: {
  // node_modules/@nuxt/schema/dist/index.d.ts 2239
  plugins: [
    UnoCSS({
      presets: [
        presetTypography(),
        presetAttributify(),
        presetIcons(),
      ],
    }),
  ],
},

jerrywu001 avatar Feb 17 '22 08:02 jerrywu001

Any other solution using vite and ssr?

b-avb avatar Mar 28 '22 16:03 b-avb

/cc @antfu Can you please confirm if upgrading to vite-node resolves this issue?

pi0 avatar Mar 28 '22 16:03 pi0

Just checked, it works with vite-node, with:

export default defineNuxtConfig({
  experimental: {
    viteNode: true
  }
})

However, even it works in the runtime, the warning is still thrown by Vite. To bypass the warning, add /* @vite-ignore */ to your import statement:

const pkg = await import(/* @vite-ignore */ '~/' + 'package.json').then((r) => r.default);

/cc @pi0 @patak-dev do you think we should be an option for vite to bypass this warning in this condition, or maybe this is just an anti-pattern we should ask users to be explicit about it?

antfu avatar Mar 29 '22 07:03 antfu

We have a PR that should further help here:

  • https://github.com/vitejs/vite/pull/7485

About the warning, I think it is too strict. But these are quite useful in most cases. I wonder if we should have a global option to disable them, or if we should not warn by default and have a new flag that would warn about "possible" issues that users could use to debug these problems.

patak-dev avatar Mar 29 '22 10:03 patak-dev

Now, I try to use vite-plugin-dynamic-import to resolve this problem.
But in the end, I hope it can be integrated into vite.

import { defineNuxtConfig } from 'nuxt3';
import dynamicImport from 'vite-plugin-dynamic-import';

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
  vite: {
    plugins: [
      dynamicImport(),
    ],
  },
});


2022-07-28

You may got the following error.

ERROR Unexpected token (1:0)

caoxiemeihao avatar Mar 31 '22 10:03 caoxiemeihao

antfu

i Vite server using experimental vite-node...

<script setup>
import { defineAsyncComponent } from 'vue'

const themeName = "brand1";
const currentFile = "Product";
const AsyncComp = defineAsyncComponent(() => import(`./themes/${themeName}/products/${currentFile}.vue`));
</script>

<template>
  <div>
    <Component :is="AsyncComp" />
  </div>
</template>
[nuxt] [request error] Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'
  at new NodeError (node:internal/errors:372:5)  
  at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1120:11)  
  at defaultResolve (node:internal/modules/esm/resolve:1200:3)  
  at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)  
  at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)  
  at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)  
  at link (node:internal/modules/esm/module_job:78:36)

antoine-1 avatar May 06 '22 10:05 antoine-1

So, somebody resolve this issue? Can't create Icon.vue component on the server side, getting same error(

silencerspirit avatar Jun 17 '22 22:06 silencerspirit

Resolve problem by creating functional component

silencerspirit avatar Jun 21 '22 19:06 silencerspirit

Now, I try to use vite-plugin-dynamic-import to resolve this problem. But in the end, I hope it can be integrated into vite.

import { defineNuxtConfig } from 'nuxt3';
import dynamicImport from 'vite-plugin-dynamic-import';

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
  vite: {
    plugins: [
      dynamicImport(),
    ],
  },
});

Cloud you please provide some demo on how to use this? I try this plugin but got Cannot read properties of undefined (reading 'stubModule') everytime.

zhouzilong2020 avatar Jun 25 '22 03:06 zhouzilong2020

@zhouzilong2020 vite-plugin-dynamic-import is easy to use, It may not be the cause of your BUG.
Can you provide a minimized demo? I may need to Debug it.

caoxiemeihao avatar Jun 25 '22 06:06 caoxiemeihao

If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 
  at <[id] onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > key="/article/view/47492998283395072" > 

mlsjla avatar Jun 29 '22 05:06 mlsjla

I think this issue has been fixed? https://github.com/vitejs/vite/blob/v3.0.4/packages/vite/CHANGELOG.md#304-2022-07-29

engenes avatar Jul 30 '22 17:07 engenes

Indeed, besides, since rc.9 vite-node is the new default. This issue should be closed. cc @pi0

ennioVisco avatar Sep 07 '22 12:09 ennioVisco

Thanks! Example: https://stackblitz.com/edit/github-l4ercq.

danielroe avatar Sep 07 '22 13:09 danielroe

@danielroe I'm trying to dynamically import images from the assets folder, using your stackblitz example.

<script setup>
const val = 'img';
const img = await import(`~/assets/images/${val}.png`).then((r) => r.default);
</script>

But I get the following error : TypeError: Failed to resolve module specifier '~/assets/images/img.png'

Is it the right way of doing this ? What am I doing wrong ?

lacorde avatar Sep 09 '22 09:09 lacorde

@lacorde That sounds right. What's not working? Do you have a reproduction?

danielroe avatar Sep 09 '22 10:09 danielroe

@danielroe Ok, took some time, but I found the issue.

It seems that the dynamic import is not working inside Nuxt components that aren't top level components (it works in app.vue and pages). See the following reproduction : https://stackblitz.com/edit/github-l4ercq-4h6epp

Look for the following error in console : TypeError: Failed to resolve module specifier '~/assets/images/home/img.png'

lacorde avatar Sep 09 '22 14:09 lacorde