未捕获的类型错误:__webpack_require__(…).context 不是函数

问题描述 投票:0回答:4

当我尝试使用此代码动态导入 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

这是为什么呢?如何解决这个问题?我错过了什么?

webpack webpack-4
4个回答
28
投票

角度15

从 Angular 14 升级到 Angular 15 后,我的应用程序中遇到了类似的问题。我通过编辑 angular.json 文件解决了这个问题,并在项目

"test"
中通过删除更改其
"options"
"main": "src/test.ts",
并添加以下内容:
"polyfills": ["zone.js/testing"],

然后
src/test.ts

文件就可以删除了

    


9
投票

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

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

旁注:您要求查找从“./”向下的所有内容(递归:您将该标志设置为

true

),但只接受一个文件:基础文件夹中的

index.js
。如果这就是你想要的,我建议将递归标志更改为 false —— 它会更快。
    


9
投票
角度15

将 Angular 从 14 更新到 15 后,我遇到了同样的错误。但我在应用程序逻辑中使用 require.context - 所以删除测试文件对我来说还不够。

相反,我将 require.context() 替换为

import.meta.webpackContext()

之前:

(require as any).context( 'frontmatter-markdown-loader!./blog-content/', true, /^\.\/.+\.md$/ )

之后:

(import.meta as any).webpackContext( 'frontmatter-markdown-loader!./blog-content/', { recursive: true, regExp: /^\.\/.+\.md$/ } )



3
投票
文档链接

文档中有一句话

The arguments passed to require.context must be literals

。 第三个参数应该是像

/^index.js$/
这样的文字。当我使用
new RegExp()
时,我遇到了同样的错误
    

© www.soinside.com 2019 - 2024. All rights reserved.