Giter Club home page Giter Club logo

vite-plugin-dynamic-import's Introduction

vite-plugin-dynamic-import

Enhance Vite builtin dynamic import

NPM version NPM Downloads awesome-vite

English | 简体中文

✅ Alias
✅ Bare module(node_modules)
✅ Compatible @rollup/plugin-dynamic-import-vars limitations
✅ Webpack-like behavior

Install

npm i vite-plugin-dynamic-import -D

Usage

import dynamicImport from 'vite-plugin-dynamic-import'

export default {
  plugins: [
    dynamicImport(/* options */)
  ]
}

cases 👉 vite-plugin-dynamic-import/test

node_modules

dynamicImport({
  filter(id) {
    // `node_modules` is exclude by default, so we need to include it explicitly
    // https://github.com/vite-plugin/vite-plugin-dynamic-import/blob/v1.3.0/src/index.ts#L133-L135
    if (id.includes('/node_modules/foo')) {
      return true
    }
  }
})

API

dynamicImport([options])

export interface Options {
  filter?: (id: string) => boolean | void
  /**
   * ```
   * 1. `true` - Match all possibilities as much as possible, more like `webpack`
   * see https://webpack.js.org/guides/dependency-management/#require-with-expression
   * 
   * 2. `false` - It behaves more like `@rollup/plugin-dynamic-import-vars`
   * see https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#how-it-works
   * ```
   * 
   * @defaultValue true
   */
  loose?: boolean
  /**
   * If you want to exclude some files  
   * e.g `type.d.ts`, `interface.ts`
   */
  onFiles?: (files: string[], id: string) => typeof files | void
  /**
   * Custom importee
   * 
   * e.g. - append `\/*@vite-ignore*\/` in front of importee to bypass to Vite
   */
  onResolve?: (rawImportee: string, id: string) => typeof rawImportee | void
}

How and why?

We assume that the project structure is as follows

├─┬ src
│ ├─┬ views
│ │ ├─┬ foo
│ │ │ └── index.js
│ │ └── bar.js
│ └── router.js
└── vite.config.js
// vite.config.js
export default {
  resolve: {
    alias: {
      // "@" -> "/User/project-root/src/views"
      '@': path.join(__dirname, 'src/views'),
    },
  },
}

Dynamic import is not well supported in Vite, such as

  • Alias are not supported
// router.js
 import(`@/views/${variable}.js`)
  • Must be relative
// router.js
 import(`/User/project-root/src/views/${variable}.js`)
  • Must have extension
// router.js
 import(`./views/${variable}`)

We try to fix these problems

For the alias in import(), we can calculate the relative path according to importer

// router.js
 import(`./views/${variable}.js`)

If the import path has no suffix, we use glob to find the file according to UserConfig.resolve.extensions and supplement the suffix of the import path.
So we need to list all the possibilities

  1. transpire dynamic import variable, you can see @rollup/plugin-dynamic-import-vars

./views/${variable} -> ./views/*

  1. generate runtime code
- // import(`./views/${variable}`)
+ __variableDynamicImportRuntime(`./views/${variable}`)

+ function __variableDynamicImportRuntime(path) {
+   switch (path) {
+     case 'foo':
+     case 'foo/index':
+     case 'foo/index.js':
+       return import('./views/foo/index.js');
+ 
+     case 'bar':
+     case 'bar.js':
+       return import('./views/bar.js');
+ }

vite-plugin-dynamic-import's People

Contributors

caoxiemeihao avatar gkhelio avatar higuaifan avatar lee-si-yoon avatar shooterrao avatar yejimeiming avatar youngleish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vite-plugin-dynamic-import's Issues

Can not support nested try

For example

    try {
        const markdown = await import(`./docs${Pathfile}.md`);
        md = markdown;
    } catch (e) {
        try {
            const markdown = await import(`./docs${Pathfile}/README.md`);
            md = markdown;
        } catch (e) {
            status = "404";
        }
    }

It throws the following error when compiling

Identifier '__variableDynamicImportRuntime0__' has already been declared (Note that you need plugins to import files that are not JavaScript)
file: xxxxxxxx/index.vue:107:9
105: 
106: export default _sfc_main// ---- dynamic import runtime functions --S--
107: function __variableDynamicImportRuntime0__(path) {
              ^
108:   switch (path) {
109:     case '../docs/privacy':

Source map generation warning

When building with vite, I get the following warning:

WARN  Sourcemap is likely to be incorrect: a plugin (vite-plugin-dynamic-import) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help

dynamic import not include subfolder

I have this case
import(./extensions/${extension}.tsx)

in the extensions folders I have:

extensions/Test.tsx
extensions/subfolder/Test1.tsx

the plugin consider only a files in extensions folder.

Webpack instead consider also all subfolders with the same dynamic import.

How can configure the plugin for have the same webpack beaviour?

Thanks

Imports don't work within defineAsyncComponent() in Vue 2/3

Imports don't work when inside defineAsyncComponent() for Vue 2/3

  const Icon = defineAsyncComponent(
    () => import(`module-name/icons/${name}.svg`)
  )

Vite Config:

export default {
  plugins: [
    vue(),
    dynamicImport(),
  ],
  resolve: {
    extensions: [
      '.mjs',
      '.js',
      '.mts',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue',
      '.jpg',
      '.png',
      '.svg',
    ],
  },
}

🐞: `import(node_modules/xxx)` not works

while using dynamicImports , if .ts used 'a: Types', throw an error
[vite] Internal server error: Unexpected token

import { ReportHandler } from 'web-vitals';

export const reportWebVitals = (onPerfEntry?: ReportHandler) => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

Dynamically-imported chunks import other dynamically-imported chunks that they shouldn't

Sorry for the confusing title. Allow me to quickly explain:

I'm on the latest versions of this plugin and vite. I have this code which dynamically imports a module:
const chart = await import(`@/renderers/${renderer}/${renderer}.js`); (That's a link, in case you want to see the source code)

Here's a short description of my usage:

  1. At run time, that line will choose 1 module out of a few available options.
  2. These modules share a few common imports, and all of them also have exclusive dependencies, that are not imported by any other module.
  3. The app is also built so that only one of these modules is ever called, so they never run simultaneously.
  4. These modules also don't import each other, and naturally, they don't import the exclusive dependencies of the other modules.

In reality, however, my bundle ends up with these modules importing each other:

  "assets/echarts.renderer.4cf1a1d8.js": {
    "chunkName": "echarts.renderer",
    "isDynamicEntry": true,
    "imports": [
      "assets/workerpool.47e82dea.js", // dependency of a common import, should be imported
      "assets/echarts.f2fcefab.js", // exclusive dependency, should be imported
      "assets/d3fc.renderer.7df595b8.js" // another top-level module: SHOULD NOT BE IMPORTED
    ]
  },
  "assets/lightningchart.renderer.b6d85ecf.js": {
    "chunkName": "lightningchart.renderer",
    "isDynamicEntry": true,
    "imports": [
      "assets/d3fc.renderer.7df595b8.js", // another top-level module: SHOULD NOT BE IMPORTED
      "assets/echarts.renderer.4cf1a1d8.js", // another top-level module: SHOULD NOT BE IMPORTED
      "assets/lcjs.2f258342.js" // exclusive dependency, should be imported
    ]
  },
  "assets/uplot.renderer.ba13ce3a.js": {
    "chunkName": "uplot.renderer",
    "isDynamicEntry": true,
    "imports": [
      "assets/d3fc.renderer.7df595b8.js", // another top-level module: SHOULD NOT BE IMPORTED
      "assets/echarts.renderer.4cf1a1d8.js", // another top-level module: SHOULD NOT BE IMPORTED
      "assets/uplot.a2bc4425.js", // exclusive dependency, should be imported
      "assets/d3.7530ac4e.js", // dependency of another top-level module: SHOULD NOT BE IMPORTED
      "assets/vendor.ce91b36d.js", // dependency, should be imported
      "assets/workerpool.47e82dea.js", // dependency of a common import, should be imported
      "assets/echarts.f2fcefab.js" // dependency of another top-level module: SHOULD NOT BE IMPORTED
    ]
  },

Is there any way to control this behavior? Thanks a lot!!!

Using pnpm, vite-plugin-dynamic-import Cannot find module 'vite'

failed to load config from /Users/toma/dev/multi-charts-comparison/vite.config.js
error when starting dev server:
Error: Cannot find module 'vite'
Require stack:
- /Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite-plugin-dynamic-import/dist/index.js
- /Users/toma/dev/multi-charts-comparison/vite.config.js
- /Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite/dist/node/chunks/dep-689425f3.js
- /Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite/dist/node/cli.js
- /Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite/bin/vite.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Module.<anonymous> (/Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite-plugin-dynamic-import/dist/index.js:9:14)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .js] (/Users/toma/Library/pnpm/global/5/node_modules/[email protected]/node_modules/vite/dist/node/chunks/dep-689425f3.js:62009:13)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
 ELIFECYCLE  Command failed with exit code 1.

Hi, it's me again :)

I switched to a git branch, and now this started happening. When starting vite dev with pnpm, vite-plugin-dynamic-import can't find Vite, even though Vite is installed and is the starting point of the script... (vite.config.js). I tried reinstalling node_modules & tried updating versions. It only happens with pnpm. Do you have an idea?

Thank you very much!

[vite-plugin-dynamic-import] Generated runtime code has redundant judgment rules in some cases

For the following dynamic import

import(`./components/${singlePathName}/index.vue`)

If singlePathName is "A" or "B", in the following generated code, case "./components/A" and case "./components/A/index" are not necessary

switch (n) {
    case "./components/A":
    case "./components/A/index":
    case "./components/A/index.vue":
        return ...;
    case "./components/B":
    case "./components/B/index":
    case "./components/B/index.vue":
        return ...;
    default:
        ....

Failed to parse vite-plugin-federation

I want to use it with vite-plugin-federation, but I found that vite-plugin-dynamic-import cannot be resolved.

vite.config.js

plugins: [
      vue(),
      dynamicImport(),
      federation({
        name: 'edoms-runtime',
        remotes: {
          'remote-ui': 'http://localhost:8001/assets/remoteEntry.js',
        },
        shared: ['vue', 'element-plus'],
      }),
    ],

main.ts

edomsApp.component(
  'UiButton',
  defineAsyncComponent(async () => {
    const component = 'button';
    // @ts-ignore
    const remoteUi = await import(`remote-ui/${component}`);
    return remoteUi.default.component;
  })
);

result

X [ERROR] [plugin vite-plugin-dynamic-import:pre-bundle] invalid import "import(`remote-ui/${component}`)". Variable bare imports are not supported, imports must start with ./ in the static part of the import. For example: import(`./foo/${bar}.js`).

image

Source Maps and Line Numbers are not correct

Hello,

The source maps are not correct, for example if I use a console.log('hi') in line 30, it just points me to line of the function component definiton (eg function MyComponent() {...} )

Dynamic import not working Windows

In version 1.2.7 dynamic imports are working fine on Windows, but starting from 1.3.0 there's an issue (maybe a regression of #38?).

1.2.7

Dynamic imports are working on Windows, macOS & Ubuntu 22.04.

>= 1.3.0

Starting from 1.3.0 (same issue in 1.4.x & 1.5.0 I get the following error messages:

[vite-plugin-dynamic-import] no files matched: import(`@/components/icon/${path}/${upperFirstName}`)
   file: C:\Users\chris\Documents\demo\src\mixins\iconLoadMixin.js             
[vite-plugin-dynamic-import] no files matched: import(`@/components/cms/${type}`)     
   file: C:\Users\chris\Documents\demo\src\mixins\cmsJsonMixin.js

The same repository works just fine with macOS & Ubuntu 22.04, it it's probably related to the Windows path separator.

Please let me know if you need anything to reproduce the issue.

`// [vite-plugin-dynamic-import] runtime -S-` header missing in compiled source

Using createServer are there any scenarios where this plugin would not add // [vite-plugin-dynamic-import] runtime -S- to the compiled source code?

I'm running into a situation where this plugin seems to be outputting the // [vite-plugin-dynamic-import] runtime -S- header (and rest of the dynamic code) to the compiled files in some circumstances, but not others, using the same application code.

Have you seen this before?

Ts import type incorrect I am not sure what cause

  // package.json
  "vite": "^3.0.0",
  "vite-plugin-dynamic-import": "^1.0.0",
// vite.config.ts
import dynamicImport from 'vite-plugin-dynamic-import'
plugins: [
    // @ts-expect-error
    dynamicImport.default(), // Does not match the document, and the TS prompt is incorrect
]

I don't know. Possible cause?

  1. Is it just the wrong type of export?
  2. allowSyntheticDefaultImports: true // Has nothing to do with this configuration
  3. package.json "type": "module", // Does it matter?

Bare imports do not work in monorepos

In monorepos, the web app is just one package (subdirectory) among many packages under the same parent directory.
The Vite config file exists under the web app's subdirectory, and config.root is set to that same directory.
Note that node_modules is shared among all of those packages, and resides directly under the parent directory. There is nothing under the node_modules subdirectory under the web app, unless a package version required by the web app differs from the package version required by the rest of the monorepo.

Unfortunately, this plugin looks for node_modules under the web app's subdirectory, and not under the parent directory:

const node_modules = path.posix.join(this.config.root, 'node_modules')

So, it does not work in monorepos.
Instead, it should go recursively up the directory tree, searching for node_modules at each level.
In other words, it should match the algorithm used by require() in Node.js: https://nodejs.org/api/modules.html#all-together
Another example that implements the same algorithm: https://github.com/h2non/resolve-tree

The above dynamic import cannot be analyzed by Vite.

I have some code that dynamically loads the locale for use with the date-fns library:

const localeObj = await import(`date-fns/locale/${locale}/index.js`

I was able to use vite-plugin-dynamic-import to get this to work in the build by making the following changes to my vite.config.ts file:

  1. I added the import:
import dynamicImport from "vite-plugin-dynamic-import";
  1. I added configuration for the plugin to the plugins array:
plugins: [
    dynamicImport({
        loose: true,
        onFiles: (files: string[], id: string) => {
            if (id.includes("/MyFileName.tsx")) { // The file that contains the dynamic import.
                // I do not want to bundle anything in "_lib" folders.
                files = files.filter((file) => file.indexOf("/_lib/") === -1);
            }
            return files;
        },
    }),
    ...
],
  1. This was more of a cosmetic step. I added the following to name the relevant chunks with a date-fns- prefix.
build: {
    rollupOptions: {
        output: {
            chunkFileNames: (chunkInfo: PreRenderedChunk) => {
                if (
                    chunkInfo.moduleIds.some((moduleId: string) =>
                        moduleId.includes("date-fns")
                    )
                ) {
                    return "date-fns-[hash].js";
                }
                return "[name]-[hash].js";
            },
        },
    },
},

This works as intended when I perform vite build which is great! The problem is that when I try to start the project on my development workstation, it does not work.

When I perform yarn vite, the output shows my dynamic import followed by this message:

The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

I can add a /* @vite-ignore */ comment to suppress the warning, but the dynamic import does not work.

It produces this error:

 TypeError: The specifier “date-fns/locale/az/index.js” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.

Is there a way to get vite-plugin-dynamic-import to work when using vite to run the dev server?

Hide warning?

Added to my plugins config:

dynamicImport({viteIgnore: () => true}),

But I still see the following output in the console:

3:31:08 PM [vite] warning: invalid import "./assets/${file}". A file extension must be included in the static part of the import. For example: import(`./foo/${bar}.js`).
  Plugin: vite:dynamic-import-vars
  File: ...

Is there a way to hide this warning?

Aliases not working with astro

Thanks for the lib

invalid import "import(`@assets/${imageName}-${scale}x.${format}`)". Variable bare imports are not supported, imports must start with ./ in the static part of the import. For example: import(`./foo/${bar}.js`).

Config

import { defineConfig } from "astro/config";
import tailwind from "@astrojs/tailwind";
import sitemap from "@astrojs/sitemap";
import preact from "@astrojs/preact";
import { resolve } from "path";
import { normalizePath } from "vite";
import blurhash from "rollup-plugin-blurhash-as";
import image from "@astrojs/image";
import dynamicImport from "vite-plugin-dynamic-import";
// https://astro.build/config
//

export default defineConfig({
  site: "https://introvert-test.com",
  integrations: [tailwind(), sitemap(), preact()],
  vite: {
    resolve: {
      alias: { "@": normalizePath(resolve(process.cwd(), "./src")) },
    },
    plugins: [
      dynamicImport(),
      {
        ...blurhash(),
        enforce: "pre",
      },
    ],
  },
});

Dynamic imports with aliases not working running under Windows OS

The plugin is not working when using aliases in imports under Windows, but it's working in Mac OS and Linux.

This is the error: [plugin:vite-plugin-dynamic-import] invalid import "import('@/components/${path}${name}.vue')". Variable bare imports are not supported, imports must start with ./ in the static part of the import. For example: import('./foo/${bar}.js').

vite.config.ts:

resolve: { alias: { '@': resolve(__dirname, './src'), }, },

Node: 16.15.1
Vite: 2.9.9
vite-plugin-dynamic-import: 0.9.9
OS: Windows 10

默认导出不是一个函数

在Vite3.x中 import dynamicImport from "vite-plugin-dynamic-import"; dynamicImport的值是一个对象,不是一个函数

Please add a LICENSE if you are okay with people using this plugin

Hi, thanks for your work on this plugin! If you're okay with people using it, can you please add a license so it can be done legally? See GitHub's licensing documentation for more info, specifically:

You're under no obligation to choose a license. However, without a license, the default copyright laws apply, meaning that you retain all rights to your source code and no one may reproduce, distribute, or create derivative works from your work. If you're creating an open source project, we strongly encourage you to include an open source license.

The MIT license is what people commonly use for open source projects like this, including Vite itself. The GitHub documentation has information about all of the license options if you'd prefer to use something else. Thanks!

How to have a dynamic import SVG component

Hello,

I have an issue when building the Vue (2.7) app:

[plugin:vite:dynamic-import-vars] invalid import "/icons/${this.name}.svg?raw". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. For example: import(./foo/${bar}.js).

We're using this component everywhere in our application.
SwIcon.vue :

<template lang="pug">
  div
    span.block(
      :class="[styleClass, sizeClass]"
      :style="{strokeLinecap: 'round', strokeLinejoin: 'round'}"
      @click="$emit('click')"
      v-html="svgRawContent"
    )
</template>

<script>
export default {
  name: 'SwIcon',
  props: {
    name: {
      type: String,
      default: '',
    },
    unstyled: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: 'w-6 h-6',
    },
  },
  data () {
    return {
      svgRawContent: '',
    };
  },
  computed: {
    sizeClass () {
      return this.size;
    },
    styleClass () {
      return this.unstyled ? '' : 'fill-none stroke-current stroke-2';
    },
  },
  // Todo: Replace by Suspense or something else when upgrading to Vue 3 to avoid async lifecycle method
  async mounted () {
    const svgObject = await import(`/icons/${this.name}.svg?raw`);
    this.svgRawContent = svgObject.default;
  },
};
</script>

Like you can see, we have this import await import(`/icons/${this.name}.svg?raw`); which is working good in development.

I guess the problem comes from the fact that during the build phase, since it is dynamic, it is not able to bundle the svg since it does not know them.

But then, how can I keep a similar component and make it work? Even if it has to bundle the whole icon's folder, it's not a big deal if it's lazy loaded.

Thanks in advance, I appreciate it ❤️

Internal server error: Cannot use 'import.meta' outside a module

When upgrading from 1.2.7 to 1.3.x, I got the following error:

[vite] Internal server error: Cannot use 'import.meta' outside a module (1:0)

Further inspection, the error comes from using the lib acorn, saying that "import.meta" can't be used on scripts.

I am using a vite project with hmr. When running vite dev, vite will inject import.meta.hot in the compiled bundle. es-module-lexer will read the bundle and extract all imports, including import.meta.*. When you call acorn parse, you don't specify the sourceType, and the default value to that is 'script'. When it catches 'import.meta', it will throw this error.

Reverting to 1.2.7 solves this problem.

Possible solution would be to pass sourceType value as option of acorn.

Cannot get it to work in SvelteKit...

I added the plugin to the config, like so:

plugins: [
  autoImport({
    components: ['./src/library'],
  }),
  sveltekit(),
  dynamicImport(),
  // etc....

...then tried to use it in a svelte component, like so:

let Component;
onMount(async () => {
  // Component = (await import(`../library/${component}.svelte`)).default <-- this works, btw, but not ideal...
  Component = (await import(`@library/${component}.svelte`)).default
})

..and got the following error in the console:

10:38:54 AM [vite] warning: 
/Users/rchrdnsh/Code/Svelte/RYKR-kit/src/library/ContentCard.svelte
1375|   onMount(async () => {
1376|           // Component = (await import(`../library/${component}.svelte`)).default
1377|           $$invalidate(11, Component = (await import(`@library/${component}.svelte`)).default);
   |                                               ^
1378|   });
1379|  
The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

...but it also does not work in the app either...

...so, dunno what to do to make it work (shrug emoji)

Any chance for dynamic imports with absolute paths

Hello,

I was wondering if there any chance to have this plugin work with dynamic import and absolute paths, that was really good to me when working with CRA, i suppose this is supported by webpack or so, but any idea of how getting this done.

Thanks in advance

Build error when using the plugin in Vite.config

I used the 'vite-plugin-dynamic-import' in my Vite.config + Vue app. This is my vite.config :
`
///
import { fileURLToPath } from 'url'
import VueI18n from '@intlify/vite-plugin-vue-i18n'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import dynamicImport from 'vite-plugin-dynamic-import'
// es
import { visualizer } from "rollup-plugin-visualizer";
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import DefineOptions from 'unplugin-vue-define-options/vite'
import { defineConfig, type PluginOption } from 'vite'
import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'
import vuetify from 'vite-plugin-vuetify'
import { url } from 'inspector';

export default defineConfig({
plugins: [
vue(),
vueJsx(),
dynamicImport(),
vuetify({
styles: {
configFile: 'src/styles/variables/_vuetify.scss',
},
}),

Pages({
  exclude: ['src/pages/**/components/**','src/pages/**/i18n/**','src/pages/**/models/**'],

  onRoutesGenerated: routes => [
    // Email filter
    {
      path: '/apps/email/:filter',
      name: 'apps-email-filter',
      component: '/src/pages/apps/email/index.vue',
      meta: {
        navActiveLink: 'apps-email',
        layoutWrapperClasses: 'layout-content-height-fixed',
      },
    },

    // Email label
    {
      path: '/apps/email/label/:label',
      name: 'apps-email-label',
      component: '/src/pages/apps/email/index.vue',
      meta: {
        // contentClass: 'email-application',
        navActiveLink: 'apps-email',
        layoutWrapperClasses: 'layout-content-height-fixed',
      },
    },
    ...routes,
  ],
}),
Layouts(),
Components({
  dirs: ['src/@core/components', 'src/views/demos'],
  dts: true,
}),

AutoImport({
  imports: ['vue', 'vue-router', '@vueuse/core', 'vue-i18n', 'pinia','vitest'],
  dts:true,
  vueTemplate: true,
}),
VueI18n({
  runtimeOnly: true,
  compositionOnly: true,
  include: [
    fileURLToPath(new URL('./src/plugins/i18n/locales/**', import.meta.url)),
  ],
}),
DefineOptions(),

visualizer() as PluginOption

],
test:{
globals:true,
environment: 'happy-dom',
},
define: { 'process.env': {} },
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
'@themeConfig': fileURLToPath(new URL('./themeConfig.ts', import.meta.url)),
'@core': fileURLToPath(new URL('./src/@core', import.meta.url)),
'@layouts': fileURLToPath(new URL('./src/@layouts', import.meta.url)),
'@configured-variables': fileURLToPath(new URL('./src/styles/variables/_template.scss', import.meta.url)),
'@axios': fileURLToPath(new URL('./src/plugins/axios', import.meta.url)),
'@Validators': fileURLToPath(new URL('./src/@core/utils/validators', import.meta.url)),
'apexcharts': fileURLToPath(new URL('node_modules/apexcharts-clevision', import.meta.url)),

},

},
build: {
target: 'esnext',
chunkSizeWarningLimit: 5000,
},
optimizeDeps: {
exclude: ['vuetify'],
entries: [
'./src/**/*.vue',
],
},
})
`
When I build my project. the following error appears:

promises' is not exported by __vite-browser-external, imported by node_modules/@iconify/tools/lib/misc/scan.mjs
import { promises } from 'fs'

how can handle this issue?

when this method in node_modules

i create a method to use dynamic import, when this method not in node_modules is correct。

but when this method is build and published to npm, there was something wrong

method.exp

export function generateRoutes(path, title, children, attrs?: Partial<RouteItemExtendMeta>) {
  const _attrs = pick(attrs, ['component']);
  const noInMeta = ['name', 'redirect', 'component'];
  const meta_attrs = omit(attrs, noInMeta);

  joinParentPath(children, path);

  const _routes = {
    path,
    // redirect: attrs?.redirect ? attrs.redirect : _redirect,
    children: generateChildRoutes(children, attrs?.dirName, attrs?.isIndex),
    ..._attrs,
    meta: {
      title,
      ...meta_attrs
    }
  };

  generateRouteRedirect(_routes as RouteRecordItem);

  return _routes;
}

export function generateChildRoutes(routes, dirName, isIndex) {
  const noInMeta = ['path', 'title', 'name', 'children', 'component', 'redirect'];

  return routes.map((item) => {
    const meta_item = omit(item, noInMeta);

    const _path = item.path.includes('/') ? item.path.split('/') : [item.path];

    let compPath = item.path.includes('/:') ? item.path.split('/:')[0] : item.path;

    if (item.hideParPath) {
      const compPaths = compPath.split('/');
      const deleteNum = isBoolean(item.hideParPath) ? 1 : item.hideParPath;
      compPaths.splice(compPaths.length - (deleteNum + 1), deleteNum);
      compPath = compPaths.join('/');
    }

    const comp = item.component
      ? item.component
      : (!item.generateComp && item.children?.length) || isUrl(item.path)
      ? null
      : () => import(`@/${dirName}${item?.isIndex || (!isBoolean(item?.isIndex) && isIndex) ? compPath + '/index' : compPath}.vue`);

    const route_item = {
      ...pick(item, ['path', 'redirect']),
      component: comp,
      children: item.children?.length ? generateChildRoutes(item.children, dirName, isIndex) : null,
      meta: {
        ...meta_item,
        title: item?.title || _path[_path.length - 1]
      }
    };

    delObjAttrNotExist(route_item, true);

    return route_item;
  });
}

image

Cannot find module 'vite-plugin-utils' or its corresponding type declarations.

After checking the vue-tsc types, errors are displayed in the console, but the plugin works correctly.
image

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "module": "ESNext",
        "target": "ESNext",
        "strict": true,
        "moduleResolution": "Node",
        "sourceMap": true,
        "allowJs": true,
        "resolveJsonModule": true,
        "useDefineForClassFields": true,
        "jsx": "preserve",
        "noImplicitThis": true,
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "isolatedModules": true,
        "preserveValueImports": true,
        "importsNotUsedAsValues": "error",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "skipLibCheck": true,
        "types": [
            "vitest/globals"
        ]
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "./**/*.ts",
        "./**/*.vue",
        "commitlint.config.js",
        "vite.config.ts"
    ]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.