微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有一个项目,我想在其中使用 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


我得到的错误

(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.

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

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


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

  1. 尚未找到 require.context() 的导入替代方案
  2. import() 它是异步的,这会使我的代码失败,因为 vue-router 不等待。可能是让它等待的变通方法,但太黑了。

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

欢迎任何答案,感谢您的时间:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。