关于webpack-dev-server:vue批量导入文件篇一

14次阅读

共计 1845 个字符,预计需要花费 5 分钟才能阅读完成。

序言

在咱们创立路由的时候,会发现如果所有的路由都在一个文件内,那么当我的项目路由多的时候,就会呈现路由难找,路由跟路由不在一块等状况呈现(没保护好)。
所以,为了防止这种状况,咱们能够应用模块化这种思维来解决问题。
那么,问题就来了,当模块多的时候,一个个的导入就很浪费时间,须要反复 引入 – 赋值 这一过程,所以,咱们是不是能让程序来帮咱们做这一步骤呢,那么咱们岂不是能够欢快游玩了。


一、webpack

require.context


依照官网解释,该办法能够在构建时在代码中解析要搜寻的目录。艰深的来说,就依据你给出的规定,而后找到符合条件的文件,而后在构建的时候主动生成咱们之前须要手动导入的那些代码。

/**
 * 能够看出该办法承受 4 个参数
 * @param {string} directory 须要搜寻的目录
 * @param {boolean} useSubdirectories 是否搜寻子目录,默认 true
 * @param {regExp} regExp 文件匹配规定 默认 /^\.\/.*$/
 * @param {string} mode 模式,默认 sync
 * @return {function} function(resolve, keys, id)
 */
require.context(
  directory,
  (useSubdirectories = true),
  (regExp = /^\.\/.*$/),
  (mode = 'sync')
)

/**
 * 该办法返回一个函数,具备 3 个属性:resolve、keys、id
 * resolve{function},返回解析申请的模块 ID
 * keys{function},返回正则匹配的文件名称数组
 * id{string},上下文模块的模块 ID
 */
// 例子,搜寻当前目录下的 modules,不须要搜寻 modules 子目录,匹配规定是所有的 js 文件
require.context('./modules', false, /\.js$/);
/**
 * 残缺例子,主动导入路由模块
 * 目录
 * --> modules
 * ---- home.js
 * ---- system.js
 */
(r => r.keys().map(key => r(key).default))(require.context('./modules', false, /\.js$/))

// console
[{
  path: '/home'
  name: 'home',
  component: () => import('@/views/home'),
}, {
  path: '/system'
  name: 'system',
  component: () => import('@/views/system'),
}]

二、vite

import.meta.glob


依照官网解释,该办法是一个懒加载办法,通过动静导入实现,与 import.meta.globEager 的区别只是一个同步,一个异步,视状况应用。

const modules = import.meta.globEager('./modules/*.ts');
let routes = [];

for (const key in modules) {modules[key]().then((mod) => {routes.push(mod.default);
  })
}

// console
[{
  path: '/home'
  name: 'home',
  component: () => import('@/views/home/index.vue'),
}, {
  path: '/system'
  name: 'system',
  component: () => import('@/views/system/index.vue'),
}]

import.meta.globEager


依照官网解释,该办法是一个同步办法,可间接引入匹配的模块

const modules = import.meta.globEager('./modules/*.ts');
let routes = [];

for (const item of Object.values(modules)) {routes.push(item.default);
}

// console
[{
  path: '/home'
  name: 'home',
  component: () => import('@/views/home/index.vue'),
}, {
  path: '/system'
  name: 'system',
  component: () => import('@/views/system/index.vue'),
}]

参考

webpack
vite

正文完
 0