亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

VUE3+vite項目中動態(tài)引入組件與異步組件的詳細(xì)實例

 更新時間:2022年09月20日 09:25:57   作者:球球不吃蝦  
在做vue3項目中時,每次使用都需要先進(jìn)行引入,下面這篇文章主要給大家介紹了關(guān)于VUE3+vite項目中動態(tài)引入組件與異步組件的相關(guān)資料,需要的朋友可以參考下

一、全量注冊,隨用隨取

1. 把項目中所有vue文件注冊成異步組件。

const app = createApp(App);
function registerGlobalAsyncComponents(app: VueApp) {
  const modules = import.meta.glob('./**/*.vue');
  for (const path in modules) {
    const result = path.match(/.*\/(.+).vue$/);
    if (result) {
      const name = result[1];
      const component = modules[path];
      app.component(name, defineAsyncComponent(component));
    }
  }
}

2. 獲取組件

在setup函數(shù)獲取組件

const internalInstance = getCurrentInstance();
// 摟一眼,看看注冊的組件名字是啥
console.log(internalInstance.appContext.components);
// 獲取組件
internalInstance.appContext.components['你組件的名字']

3. 參考如下

Glob 導(dǎo)入

Vite 支持使用特殊的 import.meta.glob 函數(shù)從文件系統(tǒng)導(dǎo)入多個模塊:

const modules = import.meta.glob('./dir/*.js')

以上將會被轉(zhuǎn)譯為下面的樣子:

// vite 生成的代碼
const modules = {
  './dir/foo.js': () => import('./dir/foo.js'),
  './dir/bar.js': () => import('./dir/bar.js')
}

你可以遍歷 modules 對象的 key 值來訪問相應(yīng)的模塊:

for (const path in modules) {
  modules[path]().then((mod) => {
    console.log(path, mod)
  })
}

匹配到的文件默認(rèn)是懶加載的,通過動態(tài)導(dǎo)入實現(xiàn),并會在構(gòu)建時分離為獨(dú)立的 chunk。如果你傾向于直接引入所有的模塊(例如依賴于這些模塊中的副作用首先被應(yīng)用),你可以傳入 { eager: true } 作為第二個參數(shù):

const modules = import.meta.glob(‘./dir/*.js’, { eager: true })

以上會被轉(zhuǎn)譯為下面的樣子:

// vite 生成的代碼
import * as __glob__0_0 from './dir/foo.js'
import * as __glob__0_1 from './dir/bar.js'
const modules = {
  './dir/foo.js': __glob__0_0,
  './dir/bar.js': __glob__0_1
}

Glob 導(dǎo)入形式

import.meta.glob 都支持以字符串形式導(dǎo)入文件,類似于 以字符串形式導(dǎo)入資源。在這里,我們使用了 Import Reflection 語法對導(dǎo)入進(jìn)行斷言:

const modules = import.meta.glob('./dir/*.js', { as: 'raw' })

上面的代碼會被轉(zhuǎn)換為下面這樣:

// code produced by vite(代碼由 vite 輸出)
const modules = {
  './dir/foo.js': 'export default "foo"\n',
  './dir/bar.js': 'export default "bar"\n'
}

{ as: ‘url’ } 還支持將資源作為 URL 加載。

多個匹配模式

第一個參數(shù)可以是一個 glob 數(shù)組,例如:

const modules = import.meta.glob(['./dir/*.js', './another/*.js'])

反面匹配模式

同樣也支持反面 glob 匹配模式(以 ! 作為前綴)。若要忽略結(jié)果中的一些文件,你可以添加“排除匹配模式”作為第一個參數(shù):

const modules = import.meta.glob(['./dir/*.js', '!**/bar.js'])
// vite 生成的代碼
const modules = {
  './dir/foo.js': () => import('./dir/foo.js')
}

具名導(dǎo)入

也可能你只想要導(dǎo)入模塊中的部分內(nèi)容,那么可以利用 import 選項。

const modules = import.meta.glob('./dir/*.js', { import: 'setup' })
// vite 生成的代碼
const modules = {
  './dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup),
  './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup)
}

當(dāng)與 eager 一同存在時,甚至可能可以對這些模塊進(jìn)行 tree-shaking。

const modules = import.meta.glob('./dir/*.js', { import: 'setup', eager: true })
// vite 生成的代碼
import { setup as __glob__0_0 } from './dir/foo.js'
import { setup as __glob__0_1 } from './dir/bar.js'
const modules = {
  './dir/foo.js': __glob__0_0,
  './dir/bar.js': __glob__0_1
}

設(shè)置 import 為 default 可以加載默認(rèn)導(dǎo)出。

const modules = import.meta.glob('./dir/*.js', {
  import: 'default',
  eager: true
})
// vite 生成的代碼
import __glob__0_0 from './dir/foo.js'
import __glob__0_1 from './dir/bar.js'
const modules = {
  './dir/foo.js': __glob__0_0,
  './dir/bar.js': __glob__0_1
}

自定義查詢

你也可以使用 query 選項來提供對導(dǎo)入的自定義查詢,以供其他插件使用。

const modules = import.meta.glob('./dir/*.js', {
  query: { foo: 'bar', bar: true }
})
// vite 生成的代碼
const modules = {
  './dir/foo.js': () =>
    import('./dir/foo.js?foo=bar&bar=true').then((m) => m.setup),
  './dir/bar.js': () =>
    import('./dir/bar.js?foo=bar&bar=true').then((m) => m.setup)
}

二、使用@rollup/plugin-dynamic-import-vars插件

1.介紹

一個rollup插件,支持rollup中動態(tài)導(dǎo)入的變量。

This plugin requires an LTS Node version (v10.0.0+) and Rollup v1.20.0+.

2.安裝

npm install @rollup/plugin-dynamic-import-vars --save-dev

3.使用

創(chuàng)建一個rollup.config.js配置文件并導(dǎo)入插件:

import dynamicImportVars from '@rollup/plugin-dynamic-import-vars';

export default {
  plugins: [
    dynamicImportVars({
      // options
    })
  ]
};

Options
include
Type: String | Array[…String]
Default: []

Files to include in this plugin (default all).包含在這個插件中的文件(默認(rèn)全部)。

exclude
Type: String | Array[…String]
Default: []

Files to exclude in this plugin (default none).該插件中要排除的文件(默認(rèn)為無)。

warnOnError
Type: Boolean
Default: false

By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
默認(rèn)情況下,當(dāng)遇到錯誤時,插件會退出構(gòu)建過程。如果將此選項設(shè)置為true,則會拋出一個警告,并保持代碼不變。

4.How it works

When a dynamic import contains a concatenated string, the variables of the string are replaced with a glob pattern. This glob pattern is evaluated during the build, and any files found are added to the rollup bundle. At runtime, the correct import is returned for the full concatenated string.

Some example patterns and the glob they produce:

`./locales/${locale}.js` -> './locales/*.js'
`./${folder}/${name}.js` -> './*/*.js'
`./module-${name}.js` -> './module-*.js'
`./modules-${name}/index.js` -> './modules-*/index.js'
'./locales/' + locale + '.js' -> './locales/*.js'
'./locales/' + locale + foo + bar '.js' -> './locales/*.js'
'./locales/' + `${locale}.js` -> './locales/*.js'
'./locales/' + `${foo + bar}.js` -> './locales/*.js'
'./locales/'.concat(locale, '.js') -> './locales/*.js'
'./'.concat(folder, '/').concat(name, '.js') -> './*/*.js'

Code that looks like this:

function importLocale(locale) {
  return import(`./locales/${locale}.js`);
}

Is turned into:

function __variableDynamicImportRuntime__(path) {
  switch (path) {
    case './locales/en-GB.js':
      return import('./locales/en-GB.js');
    case './locales/en-US.js':
      return import('./locales/en-US.js');
    case './locales/nl-NL.js':
      return import('./locales/nl-NL.js');
    default:
      return new Promise(function (resolve, reject) {
        queueMicrotask(reject.bind(null, new Error('Unknown variable dynamic import: ' + path)));
      });
  }
}

function importLocale(locale) {
  return __variableDynamicImportRuntime__(`./locales/${locale}.js`);
}

Limitations
To know what to inject in the rollup bundle, we have to be able to do some static analysis on the code and make some assumptions about the possible imports. For example, if you use just a variable you could in theory import anything from your entire file system.

function importModule(path) {
  // who knows what will be imported here?
  return import(path);
}

To help static analysis, and to avoid possible foot guns, we are limited to a couple of rules:

Imports must start with ./ or …/.
All imports must start relative to the importing file. The import should not start with a variable, an absolute path or a bare import:

// Not allowed
import(bar);
import(`${bar}.js`);
import(`/foo/${bar}.js`);
import(`some-library/${bar}.js`);

Imports must end with a file extension
A folder may contain files you don’t intend to import. We, therefore, require imports to end with a file extension in the static parts of the import.

// Not allowed
import(`./foo/${bar}`);
// allowed
import(`./foo/${bar}.js`);
Imports to your own directory must specify a filename pattern

If you import your own directory you likely end up with files you did not intend to import, including your own module. It is therefore required to give a more specific filename pattern:

// not allowed
import(`./${foo}.js`);
// allowed
import(`./module-${foo}.js`);

Globs only go one level deep
When generating globs, each variable in the string is converted to a glob * with a maximum of one star per directory depth. This avoids unintentionally adding files from many directories to your import.

In the example below this generates ./foo//.js and not ./foo/**/*.js.

import(`./foo/${x}${y}/${z}.js`);

總結(jié)

到此這篇關(guān)于VUE3+vite項目中動態(tài)引入組件與異步組件的文章就介紹到這了,更多相關(guān)VUE3+vite動態(tài)引入組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue如何在自定義組件中使用v-model

    vue如何在自定義組件中使用v-model

    本篇文章主要介紹了vue如何在自定義組件中使用v-model,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • 簡單聊聊Vue中的計算屬性和屬性偵聽

    簡單聊聊Vue中的計算屬性和屬性偵聽

    計算屬性用于處理復(fù)雜的業(yè)務(wù)邏輯,vue提供了檢測數(shù)據(jù)變化的一個屬性watch可以通過newVal獲取變化之后的值,這篇文章主要給大家介紹了關(guān)于Vue中計算屬性和屬性偵聽的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • vue?事件獲取當(dāng)前組件的屬性方式

    vue?事件獲取當(dāng)前組件的屬性方式

    這篇文章主要介紹了vue?事件獲取當(dāng)前組件的屬性方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 在vue框架下使用指令vue add element安裝element報錯問題

    在vue框架下使用指令vue add element安裝element報錯問題

    這篇文章主要介紹了在vue框架下使用指令vue add element安裝element報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue3集成electron的過程

    vue3集成electron的過程

    本文詳細(xì)介紹了如何在Vue3項目中集成Electron,包括安裝electron和electron-builder兩個依賴,以及配置.npmrc文件和手動修改鏡像源的方法,整個過程詳細(xì)記錄了從創(chuàng)建項目、安裝依賴、修改配置、到最終打包部署的每一步
    2024-10-10
  • vue性能優(yōu)化之cdn引入vue-Router的問題

    vue性能優(yōu)化之cdn引入vue-Router的問題

    這篇文章主要介紹了vue性能優(yōu)化之cdn引入vue-Router的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • vue自定義封裝指令以及實際使用

    vue自定義封裝指令以及實際使用

    市面上大多數(shù)關(guān)于Vue.js自定義指令的文章都在講語法,很少講實際的應(yīng)用場景和用例,下面這篇文章主要給大家介紹了關(guān)于vue自定義封裝指令以及實際使用的相關(guān)資料,需要的朋友可以參考下
    2022-01-01
  • vue打包靜態(tài)資源后顯示空白及static文件路徑報錯的解決

    vue打包靜態(tài)資源后顯示空白及static文件路徑報錯的解決

    這篇文章主要介紹了vue打包靜態(tài)資源后顯示空白及static文件路徑報錯的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • vue+electron 自動更新的實現(xiàn)代碼

    vue+electron 自動更新的實現(xiàn)代碼

    這篇文章主要介紹了vue+electron 自動更新的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-02-02
  • vue3?TS?vite?element?ali-oss使用教程示例

    vue3?TS?vite?element?ali-oss使用教程示例

    這篇文章主要為大家介紹了vue3?TS?vite?element?ali-oss使用教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07

最新評論