使用 ES 模块时的 require.context() 替代方案

rol*_*oli 9 require webpack es6-modules

我有一个项目,我想使用 ES 模块并使用import而不是require.

所以我添加了package.json "type": "module".

现在有一种情况,我必须导入一些文件,而我知道的唯一方法是使用require.context.


我的文件(自动导入路由):

import { createRouter, createWebHistory } from 'vue-router'

/*
 * Auto imports routes from @/pages. It only requires a route.js file inside each page
 * */
function autoImportRoutes() {
  const filePaths = require.context('@/pages/', true, /route.js/)
  console.log(filePaths.keys())
  return filePaths.keys().map(filePath => {
    const pathWithoutLeadingDot = filePath.replace('.', '') // remove first dot of ./path-name
    return require(`@/pages${pathWithoutLeadingDot}`).default
  })
}

const routes = autoImportRoutes()

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

Run Code Online (Sandbox Code Playgroud)

我得到的错误:

(node:36528) Warning: require() of ES modules is not supported.
require() of babel.config.js from project-path\no
de_modules\@babel\core\lib\config\files\module-types.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename babel.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from project-path\package.js
on.

Run Code Online (Sandbox Code Playgroud)

如果我删除,则一切"type": "module"package.json有效,但我想知道是否有办法使这项工作有效。

我知道require.context()使用 ES 模块时(可能)是不允许的,但是如何在不使用 的情况下执行相同的功能require.context()


更新:我对此进行了一些搜索,似乎无法通过使用 ES 模块来完成我想要的操作(至少在不使用节点文件系统的情况下),原因有两个。

  1. 还没有找到进口替代品require.context()
  2. import()它是异步的,这将使我的代码失败,因为vue-router不等待。可能有解决方法让它等待,但太老套了。

所以现在,我会坚持"type": "module"package.json

欢迎任何回答,感谢您的宝贵时间:)

小智 0

您不需要(事实上,不应该)使用requirewith require.context。上下文对象本身是可调用的,并且在使用相关键调用时将需要相关模块。您的导入函数应该是:

function autoImportRoutes() {
  const filePaths = require.context('@/pages/', true, /route.js/)
  return filePaths.keys().map(filePath => {
    return filePaths(filePath).default
  })
}
Run Code Online (Sandbox Code Playgroud)