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

Dynamic glob imports does not work with vite #12806

Open
pi0 opened this issue Nov 4, 2021 · 30 comments
Open

Dynamic glob imports does not work with vite #12806

pi0 opened this issue Nov 4, 2021 · 30 comments

Comments

@pi0
Copy link
Member

pi0 commented Nov 4, 2021

Environment


  • Operating System: Linux
  • Node Version: v14.16.0
  • Nuxt Version: 3.0.0-27265876.3cd4494
  • Package Manager: npm@7.17.0
  • 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 pi0 changed the title Dynamic imports does not work with vite Dynamic glob imports does not work with vite Nov 4, 2021
@AbrahemAlhofe
Copy link

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

@pi0
Copy link
Member Author

pi0 commented Dec 10, 2021

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

@Blakeinstein
Copy link

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

@lacorde
Copy link

lacorde commented Jan 28, 2022

I would also be interested in a work around !

@Blakeinstein
Copy link

Blakeinstein commented Jan 28, 2022

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,
  ...
})

@jerrywu001
Copy link

jerrywu001 commented Feb 17, 2022

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(),
      ],
    }),
  ],
},

@b-avb
Copy link

b-avb commented Mar 28, 2022

Any other solution using vite and ssr?

@pi0
Copy link
Member Author

pi0 commented Mar 28, 2022

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

@antfu
Copy link
Member

antfu commented Mar 29, 2022

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?

@patak-dev
Copy link

We have a PR that should further help here:

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.

@caoxiemeihao
Copy link

caoxiemeihao commented Mar 31, 2022

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)

@ghost
Copy link

ghost commented May 6, 2022

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)

@silencerspirit

This comment was marked as duplicate.

@silencerspirit
Copy link
Contributor

Resolve problem by creating functional component

@zhouzilong2020
Copy link

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.

@caoxiemeihao
Copy link

caoxiemeihao commented Jun 25, 2022

@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.

@mlsjla
Copy link

mlsjla commented Jun 29, 2022

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" > 

@engenes
Copy link

engenes commented Jul 30, 2022

@ennioVisco
Copy link
Contributor

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

@danielroe
Copy link
Member

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

@lacorde
Copy link

lacorde commented Sep 9, 2022

@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 ?

Copy link
Member

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

@lacorde
Copy link

lacorde commented Sep 9, 2022

@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'

@danielroe danielroe reopened this Sep 9, 2022
@danielroe danielroe added the 3.x label Jan 19, 2023
@danielroe danielroe transferred this issue from nuxt/framework Jan 19, 2023
@AnzhiZhang
Copy link

This is bothering me, I can't even import the function of the Nuxt module
Example: https://stackblitz.com/edit/github-wtjope

@danielroe
Copy link
Member

@AnzhiZhang I think that might be an issue to raise upstream with @nuxt/content - it's not related to this issue.

@caoxiemeihao
Copy link

Actually, It is limited by Vite's resolve function, which has certain restrictions.
If we force try to match paths as mush as possible, will this break Vite's design? @poyoho

@poyoho
Copy link
Contributor

poyoho commented Mar 14, 2023

use the resolve function to replace the alias paths in importSource. Do you mean try to match paths as mush as possible before vite/dynamicImportVars plugin? I think it is ok.

@caoxiemeihao
Copy link

caoxiemeihao commented Mar 14, 2023

At present, vite-plugin-dynamic-import implements its own resolve function, only it looks i bit ugly.
vite/dynamicImportVars care to re-implement the resolve function? or as you say, we add a other plugin?

@poyoho
Copy link
Contributor

poyoho commented Mar 14, 2023

IMO, vite plugin also can get the ctx.resolve, the vite/resolve is had too many feature. And now vite/dynamicImportVars no support alias?

@caoxiemeihao
Copy link

caoxiemeihao commented Mar 14, 2023

Here some cases:

// With out ends slash
import(`./foo-${id}`)

// Only alias here
import(`@/${id}`)

// node_modules's module and mybe load the `style` files.
// e.g. cssFilePath == 'css/hero.css' || 'less/hero.less', can includes slash
import('ui-framework/theme' + cssFilePath)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

No branches or pull requests