webpackwebpack-4

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


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?


Solution

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