Uncaught TypeError: __webpack_require__(…).context is not a function

Uncaught TypeError: __webpack_require__(…).context is not a function

当我尝试使用此代码动态导入 vue 组件时:

const components = require.context('./', true, '/^index\.js$/');

我收到这个错误:

app.js:9 Uncaught TypeError: __webpack_require__(...).context is not a function
    at Module../asset/app.js (app.js:9)
    at __webpack_require__ (bootstrap:782)
    at fn (bootstrap:150)
    at Object.0 (app.293d5fe1d8a073fed37a.bundle.js:1747)
    at __webpack_require__ (bootstrap:782)
    at checkDeferredModules (bootstrap:45)
    at bootstrap:858
    at bootstrap:858

这是为什么?如何解决?我错过了什么?

尝试将第三个参数从字符串更改为正则表达式,即:

const components = require.context('./', true, /^index.js$/)

我使用了一些有效的正则表达式,还有一些我正在尝试整理的用法,它们不使用像这个这样的内联正则表达式。

Side-note:您要求从“./”向下查找所有内容(递归:您将该标志设置为 true),但只会接受一个文件:index.js 在基本文件夹中。如果这就是您想要的,我建议将递归标志更改为 false——这样会更快。

doc link

文档中有一句话The arguments passed to require.context must be literals。 第三个参数应该是像 /^index.js$/ 这样的文字。我在使用 new RegExp()

时遇到了同样的错误