19

When I am trying to import dynamically vue components using this code:

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

I am getting this error:

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

Why is that? How to fix that? What have I missed?

Victor Trusov
  • 1,057
  • 9
  • 19
webprogrammer
  • 2,393
  • 3
  • 21
  • 27

4 Answers4

21

Angular 15

I ended up here after getting a similar issue in my app after upgrading from Angular 14 to Angular 15. I solved it this way by editing the angular.json file and in the project "test" changing its "options" by removing "main": "src/test.ts", and adding this instead:

"polyfills": ["zone.js", "zone.js/testing"],

then the src/test.ts file can be removed

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • 5
    I had the same problem after updating NG 14 → 15. For me, https://stackoverflow.com/a/74572172/256646 (deleting 2 lines in `src/test.ts`) solved the problem. – hoeni Dec 27 '22 at 10:02
  • But that only explains it for tests. I have this problem in non-test code and my regex is a literal. It worked in Angular 14, now it breaks with 15. – GarfieldKlon Jan 17 '23 at 12:46
9

Try changing the third argument from a string to a regex, ie:

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

I have usages with regexes which work, and others which I'm trying to sort out, which don't use an inline regex like this one.

Side-note: you're asking to find everything from './' downward (recursive: you're setting that flag to true), but will only accept one file: index.js in the base folder. If that's all you want, I'd suggest changing the recursive flag to false -- it will be quicker.

daf
  • 1,289
  • 11
  • 16
6

Angular 15

I'm got the same error after updating Angular from 14 to 15. But I'm using require.context inside my app logic - so removing the test files wasn't enough for me.

Instead, I replaced require.context() with import.meta.webpackContext().

Before:

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

After:

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

doc link

there is a sentence The arguments passed to require.context must be literals in docs. The third argument should be a literals like /^index.js$/. I got the same error when I used new RegExp()

YuanHao
  • 21
  • 2