最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

一、全量注冊(cè),隨用隨取

1. 把項(xiàng)目中所有vue文件注冊(cè)成異步組件。

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();
// 摟一眼,看看注冊(cè)的組件名字是啥
console.log(internalInstance.appContext.components);
// 獲取組件
internalInstance.appContext.components['你組件的名字']

3. 參考如下

Glob 導(dǎo)入

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

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

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

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

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

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

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

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

以上會(huì)被轉(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 語法對(duì)導(dǎo)入進(jìn)行斷言:

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

上面的代碼會(huì)被轉(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 加載。

多個(gè)匹配模式

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

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

反面匹配模式

同樣也支持反面 glob 匹配模式(以 ! 作為前綴)。若要忽略結(jié)果中的一些文件,你可以添加“排除匹配模式”作為第一個(gè)參數(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 選項(xiàng)。

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 一同存在時(shí),甚至可能可以對(duì)這些模塊進(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 選項(xiàng)來提供對(duì)導(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.介紹

一個(gè)rollup插件,支持rollup中動(dòng)態(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)建一個(gè)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).包含在這個(gè)插件中的文件(默認(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)遇到錯(cuò)誤時(shí),插件會(huì)退出構(gòu)建過程。如果將此選項(xiàng)設(shè)置為true,則會(huì)拋出一個(gè)警告,并保持代碼不變。

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項(xiàng)目中動(dòng)態(tài)引入組件與異步組件的文章就介紹到這了,更多相關(guān)VUE3+vite動(dòng)態(tài)引入組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vee-validate vue 2.0自定義表單驗(yàn)證的實(shí)例

    vee-validate vue 2.0自定義表單驗(yàn)證的實(shí)例

    今天小編就為大家分享一篇vee-validate vue 2.0自定義表單驗(yàn)證的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-08-08
  • 詳解如何創(chuàng)建基于vite的vue項(xiàng)目

    詳解如何創(chuàng)建基于vite的vue項(xiàng)目

    vite 這個(gè)是尤大開發(fā)的新工具,目的是以后替代webpack,下面這篇文章主要給大家介紹了關(guān)于如何創(chuàng)建基于vite的vue項(xiàng)目的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11
  • vue 中swiper的使用教程

    vue 中swiper的使用教程

    本文通過實(shí)例代碼給大家介紹了vue 中swiper的使用,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-05-05
  • vue?使用el-table循環(huán)生成表格的過程

    vue?使用el-table循環(huán)生成表格的過程

    這篇文章主要介紹了vue?使用el-table循環(huán)生成表格的過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • 函數(shù)式組件劫持替代json封裝element表格

    函數(shù)式組件劫持替代json封裝element表格

    這篇文章主要介紹了為大家函數(shù)式組件劫持替代json封裝element表格的過程思路及示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • Vue中使用?Aplayer?和?Metingjs?添加音樂插件的方式

    Vue中使用?Aplayer?和?Metingjs?添加音樂插件的方式

    這篇文章主要介紹了Vue中使用?Aplayer?和?Metingjs?添加音樂插件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-08-08
  • vue elementui form表單驗(yàn)證的實(shí)現(xiàn)

    vue elementui form表單驗(yàn)證的實(shí)現(xiàn)

    這篇文章主要介紹了vue elementui form表單驗(yàn)證的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-11-11
  • vue3.0?移動(dòng)端二次封裝van-uploader實(shí)現(xiàn)上傳圖片(vant組件庫)

    vue3.0?移動(dòng)端二次封裝van-uploader實(shí)現(xiàn)上傳圖片(vant組件庫)

    這篇文章主要介紹了vue3.0?移動(dòng)端二次封裝van-uploader上傳圖片組件,此功能最多上傳6張圖片,并可以實(shí)現(xiàn)本地預(yù)覽,實(shí)現(xiàn)代碼簡單易懂,需要的朋友可以參考下
    2022-05-05
  • VUE3+mqtt封裝解決多頁面使用需重復(fù)連接等問題(附實(shí)例)

    VUE3+mqtt封裝解決多頁面使用需重復(fù)連接等問題(附實(shí)例)

    最近了解到mqtt這樣一個(gè)協(xié)議,可以在web上達(dá)到即時(shí)通訊的效果,下面這篇文章主要給大家介紹了關(guān)于VUE3+mqtt封裝解決多頁面使用需重復(fù)連接等問題的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-04-04
  • vite+element-plus項(xiàng)目基礎(chǔ)搭建的全過程

    vite+element-plus項(xiàng)目基礎(chǔ)搭建的全過程

    最近看完Vue3和Vite文檔之后,就寫了個(gè)小demo,整體感覺下來還是很絲滑的,下面這篇文章主要給大家介紹了關(guān)于vite+element-plus項(xiàng)目基礎(chǔ)搭建的全過程,需要的朋友可以參考下
    2022-07-07

最新評(píng)論

靖远县| 乡城县| 克拉玛依市| 深州市| 江阴市| 垣曲县| 新绛县| 阿鲁科尔沁旗| 迭部县| 饶阳县| 八宿县| 黄浦区| 彭泽县| 沁阳市| 乐陵市| 福建省| 伊金霍洛旗| 监利县| 宿州市| 巴彦淖尔市| 朝阳市| 鲁甸县| 宜州市| 舞阳县| 桦川县| 阿克陶县| 吴旗县| 平顶山市| 焦作市| 马龙县| 阳新县| 彭阳县| 兴业县| 盐山县| 会同县| 临西县| 大埔县| 运城市| 上虞市| 汉源县| 邯郸县|