webpack 使用ES模块时require.context()替代

brqmpdu1  于 2023-04-06  发布在  Webpack
关注(0)|答案(1)|浏览(216)

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

如果我删除,从package.json"type": "module"一切工作,但我想知道是否有一种方法,使这一工作。
我知道require.context()(可能)在使用ES模块时是不允许的,但是如何在不使用require.context()的情况下实现相同的功能呢?

**更新:**我搜索了一下,似乎不可能通过使用ES模块来做我想做的事情(至少不需要修改节点文件系统),原因有两个。

1.尚未找到require.context()的导入替代方法

  1. import()是异步的,这会使我的代码失败,因为vue-router不会等待。
    所以现在,我将坚持从package.json中删除"type": "module"
    欢迎任何回答,感谢您的时间:)
nx7onnlm

nx7onnlm1#

你不需要(事实上,不应该)将requirerequire.context一起使用。上下文对象本身是可调用的,当使用相关键调用时,将需要相关的模块。你的导入函数应该是:

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

相关问题