webpack: Uncaught TypeError: Cannot read property 'call' of undefined

I’m having an issue with webpack where if I stop watching and restart, it will build just fine, but if I edit a file and save it, the incremental build fails with this error:

Uncaught TypeError: Cannot read property ‘call’ of undefined

Hunting it down there’s a module that does not get included in the incremental change build. Best guess is the path followed to re-make the bundle file is not being followed correctly. Upon re-running (stop and start), the missing module is included.

webpack.config.js (module names changed to protect the innocent):

var webpack = require("webpack"),
    path = require('path')
    ;

module.exports = {
  entry: {
    Entry1: "./app/Entry1.js",
    Entry2: "./app/Entry2.js",
    Entry3: "./app/Entry3.js",
    Entry4: "./app/Entry4.js",
    Entry5: "./app/Entry5.js",
    Entry6: "./app/Entry6.js",
    Entry7: "./app/Entry7.js",
    Entry8: "./app/Entry8.js",
  },
  output: {
    path: path.join(__dirname, "public/js"),
    filename: "[name].bundle.js",
    chunkFilename: "[id].chunk.js"
  },
  module: {
    loaders: [
      {test: /\.js$/, loader: 'jsx-loader'}
    ]
  },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin("shared.js")
    ]
};

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 81
  • Comments: 264 (20 by maintainers)

Commits related to this issue

Most upvoted comments

Is it really a incorrect bundle/chunk file or is the file in the browser cache just old?

I am also having this issue with v1.12.2

For me the issue goes away if I disable the DedupePlugin

var Develop = _.merge({
  watch: true,
  plugins: [
    //new webpack.optimize.DedupePlugin(),
    new webpack.optimize.CommonsChunkPlugin("vendors", "vendors.js"),
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
    ),
    new ExtractTextPlugin("[name].css"),
  ]
}, Common);

So, as a temporary solution before this bug has fixed: 1.If you are using both CommonChunksPlugin and ExtractTextPlugin, make sure the allChunks option of ExtractTextPlugin is set to true; 2.If you are using HtmlWebpackPlugin, set options chunksSortMode to 'dependency' 3.If you did all operations before, trouble is still alive, try solve the dependencies by your hand.(change the order you import the scripts in html)

Please fix the issue~

In case it’s any help to others:

My issue was that the ExtractTextPlugin was used in production. By default, the plugin only extracts the text of the initially-loaded chunks. Fixing it, for me, was as simple as adding allChunks: true like so:

new ExtractTextPlugin({
  filename: cssFileName,
  allChunks: true
})

@sokra dang, this error is so annoying, it disrupts the workflow a lot. Not every time but often. I am both using multiple entry points and the commonChunkPlugin. Is this error going to gt fixed, I am not sure on how to help.

Pretty please have another look at this bug!

Happened to me also. Learned that it’s a cache issue on the server. Users where getting outdated chunks. I’ve fixed this with adding hash ([chunkhash]) to chunks, so the setting I’ve updated is : chunkFilename: '[id].chunk.[chunkhash].js',.

Hope this helps someone.

pls kill me

Sorry, I should have mentioned how I fixed it. If you look here https://github.com/AngularClass/angular2-webpack-starter/blob/b305c9a8071465ee0817a59093c9f73fd1cc7278/config/webpack.common.js#L240...L243 the chunk order is now correct via chunksSortMode: 'dependency' which will ensure this order polyfills, vendor, main which means the webpack IIFE is included in polyfills which is the first script to load

It’s interesting to see such a prominent bug seems to last forever in webpack. I’ve ditched javascript and switched to multi-platform app development using Python (the Kivy framework) for one year now and I’ve become a much happier man:)

Still, have this problem. with producation building

Adding chunksSortMode: 'dependency' to the HtmlWebpackPlugin fixed it for me, thanks @gdi2290 !

Same problem here, problem occurs after watch has detected a change and builds the bundle.

Uncaught TypeError: Cannot read property 'apply' of undefined

v1.11.0

We’ll look into this. Def seems like a problem.

I’m seeing the same issue with the latest webpack and optimization.splitChunks on.

immortal bug 😛

I’m still seeing this issue. Using the latest version v1.10.1

First build works fine, but incremental builds fail. I get the following error from my bundle: Uncaught TypeError: Cannot read property 'apply' of undefined

It seems to break on the usage of apply in this function.

function(modules) {
    // Check all modules for deduplicated modules
    for(var i in modules) {
        if(Object.prototype.hasOwnProperty.call(modules, i)) {
            switch(typeof modules[i]) {
            case "function": break;
            case "object":
                // Module can be created from a template
                modules[i] = (function(_m) {
                    var args = _m.slice(1), fn = modules[_m[0]];
                    return function (a,b,c) {
                        fn.apply(this, [a,b,c].concat(args)); // Breaks here
                    };
                }(modules[i]));
                break;
            default:
                // Module is a copy of another module
                modules[i] = modules[modules[i]];
                break;
            }
        }
    }
    return modules;
}

The hashes of the builds are different.

After a little trial’n’error I narrowed this bug down to being a caching issue. If you add cache: false it does build fine. Just that it is slow. Still a better than re-starting manually.

I hope this helps fixing the bug. Isn’t it a saying that the two most difficult things in programming are cache invalidation and …

This issue seems to go away after removing the Dedupe plugin. Related issue: https://github.com/webpack/webpack/issues/583

Remove the DedupePlugin and all work right (;

@TheLarkInn @sokra @jhnns @SpaceK33z

Is there anything that can be done around here that would make this issue easier to diagnose? Better error message? More context in the error message?

It feels every time we make a half significant change to our webpack configuration (adding/moving/removing plugins/optimisataions) we end up hitting this and have a hard time working out where the problem is sourced from since it does not have a single root problem. Given the amount of comments on this issue I’d say other people feel this pain too.

it still exists in webpack@4.21.0

setting concatenateModules: false in optimization fixed the problem in my case

@papermana Were you using arrow functions in your require.ensure()?

Btw I’m using webpack@2.2.0-rc.1

Just came across this issue myself with the following extremely simple code:

require.ensure(['./split'], require => {
    require('./split')();
});

I stepped back and thought “well to simplify this even further, let’s not use a fancy arrow here” and I changed it to this:

require.ensure(['./split'], function(require) {
    require('./split')();
});

…voila…it magically worked.

At first I assumed that this had to do with the fact that arrow functions use lexical this binding especially since many of the errors here revolve around .call(..) and .apply(..). I dug in a little further though and set some breakpoints in DevTools around the failing area.

I’m no webpack source expert (yet) so bare with my source illiteracy but it seems that every moduleId passed into the below function should be a number.

webpack_require

All is well when using a regular function as the callback to require.ensure() however when using an arrow function I noticed eventually the moduleId will end up being a string.

webpack_require_2

This is where things failed seemingly because installedModules[moduleId] would return undefined. So what I did is on the fly replaced moduleId with 2 (in my current case that was the correct moduleId of my async module).

webpack_require_3

Finally when we set module = installedModule[moduleId], module was a valid object and not undefined.

webpack_require_4

TL;DR

There seems (?) to be some issue with moduleId’s resolved value when using an arrow function in require.ensure(..) if my analysis is right?

cc: @TheLarkInn

同问,还是有这个问题。为什么问题关闭?

Nvm I have a reproducible example. New tests passing fix should coming up shortly

I’m facing the same issue with DedupePlugin. I’m using webpack 2 beta 20 and named Commons chunks - image

For everyone running into this, The problem is usually the the order if the files and webpack’s module wrap when you use CommonsChunkPlugin or HtmlWebpackPlugin

for HtmlWebpackPlugin you can manually sort your files with chunksSortMode

new HtmlWebpackPlugin({
  // ...
  chunksSortMode: function (a, b) {
    const entryPoints = ["inline","polyfills","sw-register","styles","vendor","main"];
    return entryPoints.indexOf(a.names[0]) - entryPoints.indexOf(b.names[0]);
  },
  // ...
})

for CommonsChunkPlugin the order of the when webpack creates chunks matter since they inject webpackJsonp in the main file. Here’s a simple pseudocode example (may not work) main.js

!(function(modules) {
  const bundleMap = {
    'react': 'vendor.js'
  }
  function __webpack_import__ (moduleId) {
    // if we don't have the module then load it
    if (bundleMap[moduleId]) {
      return webpackJsonp(moduleId)
    }
  }
  function  __webpack_require__ (moduleId) {
    const module = {
      exports: {}
    }
    modules[moduleId].call(module.exports, module, module.exports, __webpack_require__, __webpack_import__)
    return modules[moduleName].
  }
  function webpackJsonp (moduleId, otherModules) {
    if (modules[moduleId]) {
      // module is already registered
      return  Promise.resolve(modules[moduleId])
    }

    if (otherModules) {
      // include new modules in registry
      Object.assign(modules, otherModules)
      return Promise.resolve(__webpack_require__(moduleId))
    }

    if (moduleId) {
      return new Promise(function(resolve, reject) {
        // load async module
        const head = document.getElementsByTagName("head")[0];
        const script = document.createElement("script");
        script.onload = function done () {
          setTimeout(function() {
            resolve(window.webpackJsonp(moduleId))
          })
        }
        script.src = '/' + moduleId;
        head.appendChild(script);
      })
    }
  }
  window.webpackJsonp = window.webpackJsonp || webpackJsonp
  return __webpack_require__('./main')
}({
  './app': function (module, exports, require) {
    const React = require('react')
    const ReactDOM = require('react-dom')

    ReactDOM.render(React.createElement('div', {}, []), document.getElementById('app'))
  },
  './main': function(module, exports, require, import) {
    import('./app').then(function() {
      console.log('App Loaded')
    })
  }
}))

vendor.js

webpackJsonp(null, {
  'react-dom': function (module, exports, require) {
    //
  },
  'react': function (module, exports, require) {
    // ...
  }
})

In this pseudocode example of webpack, you can see how the order of when the files are loaded matters a lot since webpackJsonp is defined in the main file while react and react-dom are defined in vendor.js

tipe-io-logo

If you are using both CommonChunksPlugin and ExtractTextPlugin, make sure the allChunks option of ExtractTextPlugin is set to true; this seemed to be the fix for me.

See https://webpack.js.org/plugins/extract-text-webpack-plugin/#options (specifically the allChunks section)

I removed webpack.optimize.OccurrenceOrderPlugin and it became fine again.

Had the same issue without using the DedupePlugin.

I got Uncaught TypeError: Cannot read property 'call' of undefined in manifest.js.

It was pretty simple after I found the solution: I had to add chunksSortMode: 'dependency' to my HtmlWebpackPlugin because without it the index.html resulted in script tags in the wrong order (the vendor.js was the last one).

it also happens on v1.12.2.

In my case it happens in an entry point which is not included in the CommonsChunkPlugin as a chunk. If I remove the CommonsChunkPlugin it works fine.

However, I do have a few more entry points that are not included in the CommonsChunkPlugin and they work fine. The only thing that is special with this specific entry file is that the required files are not really modules. They don’t export anything. This entry point is for the marketing site of the project and it just concatenates a few scripts so it looks like this:

require('./about');
require('./copy-buttons');
require('./documentation');
require('./get-started');
require('./header');

and these files have a few jquery stuff with no use of module.exports

Re-open please?

I’m also getting this problem, using webpack 4.31.0 and SplitChunksPlugin. I’ve provided a minimal project setup that reproduces the problem: https://gitlab.com/jlapointe/codesplittingtest

I’ve tried most of the fixes suggested earlier in the thread (toggling various config fields, including concatenateModules), but no luck.

Some commonalities with previous comments:

I’m having the error

Uncaught (in promise) TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (common.js:53)
    at eval (graphiql.css?./~/css-loader!./~/resolve-url-loader:1)
    // rest of the stack trace here

webpack 2.2.1

In my case, I’m creating a commons chunk from 2 entry points, each representing an app. These apps both import the same module via code-splitting. The error is caused when trying to eval an import 'graphiql/graphiql.css'; in the module in question.

~I’ve noticed that other modules imported via code-splitting only in one of the apps don’t have this problem. Moreover, I can see in the output of weback that the corresponding CSS of the working modules are properly extracted by the ExtractTextPlugin whereas the CSS of the failed module are not.~

EDIT: all modules which import css or scss have the error in question.

EDIT 2: I’m using allChunks: true for my ExtractTextPlugin and the issue is gone. This however means that the CSS is not delivered via code-splitting but it’s build during compile time with all the other assets. I found some issues in the ExtractTextPlugin repo that perhaps are related to this.

sokra:

Error: No template for dependency: TemplateArgumentDependency happens when you have multiple webpack copies installed and used the DedupePlugin from a different copy.

https://gitter.im/webpack/webpack/archives/2015/02/04

Was able to fix it with a combination of chunk hashing and webpack route prefetching. The prefetching logic prevents the client from requesting outdated chunks, and the chunk hashing forces the chunks to update once new ones are available server side. With only one or the other, chunks either crash or fail to update. I believe this is because we have code splitting implemented in our react appRoot.

I would also like to note the often proposed solution of adding chunksSortMode: 'dependency' completely broke our update cycle and prevented the app from properly updating at all. I dont recommend it for production code.

My fix: (Webpack 4.46.0 & react 16.14.0 with HtmlWebpackPlugin)

Note: This solution only worked perfectly after the second app update as the prefetching logic must be live on the client to prevent loading outdated chunks.

Edit: This did not entirely fix our issue and the problem persists 😦

never ending…

My experience: I faced this error 2 times:

  1. had multiple webpack configs, solved by adding contenthash in
chunkFilename: '[name].[contenthash].js',
  1. had dynamic chunks with
output: {
      libraryTarget: 'umd',
    },

fixed by adding

      library: '[name]',
      umdNamedDefine: false,

I had this issue and it turns out it was because I had 2 chrome windows open with my app. I did some changes on my app, then refreshed one of those windows to see the changes and it threw this error, and it kept showing until I closed the other window, then again refresh my window and it worked. Hope this helps someone.

@louisscruz thanks, i fixing it with your method. Just adding allChunks: true as so:

new ExtractTextPlugin({
  filename: cssFileName,
  allChunks: true
})

If you’re using hard-source-webpack-plugin or babel-loader with the cacheDirectory option enabled, try deleting the contents of the cache directory; this defaults to node_modules/.cache/**. For me, this fixed the issue.

Also running into this bug, but only in production:

  • Can’t reproduce it in dev-mode
  • It only happens after some builds, one time it works, some code is changed, a new build is created, the problem occurs again.
  • It seems like a timing/race condition. I just experienced the issue on the initial load of the page, but on a refresh it was gone…
  • I also had interesting results with loading the bundles from local node server, vs CDN. The same bundle would work when loading from the local node server (single request limit?) but fail when loaded from CDN.

Running 2.1.0-beta18, with Aurelia rc update. Using 3 separate chunks (aurelia-bootstrap, aurelia, app), <script loaded in the right order (production == dev).

Removing the common-chunks plugin and just using a single entrypoint seems to fix it.

@foffer you add debug: true to the webpack.config.js same level as entry and plugins. Not within the CommonsChunkPlugin. Also note this is just a workaround that makes it less anoying, but you will now have to wait for all files to re-build. So it is far from a solution. The only thing you get out of it is that you do not manually have to re-start webpack after every change.

@airwin I am not using the DedupePlugin in development but the bug is there. So it is not caused by the DedupePlugin only.

Here people working with angular2 fight with this random wild, very dengerous error: https://github.com/AngularClass/angular2-webpack-starter/issues/456

The same Uncaught TypeError: Cannot read property 'call' of undefined bug on webpack 1.12.9.

It breaks on this line in the runtime (I’ve extract the runtime in a separate chunk, and inserted it into the html):

/******/// Execute the module function
/******/modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/

As @zbyte64 noted, disabling the DedupePlugin plugin fixes the problem.

To reproduce:

git clone https://github.com/kawing-chiu/flask-react-redux-example.git
cd flask-react-redux-example
git checkout 3b3e198a1582e8
cd client
npm install
gulp build

Then serve the content in the build/ directory and see the bug:

cd build/
python3 -m http.server 3000

😭I’m still seeing this issue. Using the latest version v1.11.0

To fix this issue, just try every enabled plugins in production mode, which means changing property values in optimization field. The fields include

removeAvailableModules?, 
removeEmptyChunks?, 
mergeDuplicateChunks?, 
flagIncludedChunks?, 
occurrenceOrder?, 
sideEffects?, 
providedExports?, 
usedExports?, 
concatenateModules?, 
splitChunks?, 
runtimeChunk?, 
noEmitOnErrors?, 
checkWasmTypes?, 
mangleWasmImports?, 
moduleIds?, 
chunkIds?, 
namedModules?, 
hashedModuleIds?, 
namedChunks?, 
portableRecords?,
minimize?, 
minimizer?, 
nodeEnv?`

And most of the time, disable removeEmptyChunks, mergeDuplicateChunks, occurrenceOrder and concatenateModules will help.

I had this problem suddenly, and the only thing I did was change devtool to 'source-map' in the development webpack config.

Everything was fine before that, but my working copy was broken no matter what I did. Even though I reverted the change, I kept getting the erro. I’ve tried: 1) changing setting back, 2) stashing working copy changes, 3) deleting node_modules, 4) git clean -dxf, all to no avail.

I tried reverting back to before we added CommonsChunkPlugin, and it was working then, and then I checked out HEAD again, and it wasn’t working. Removing @babel/polyfill as @louisscruz mentioned resolved the issue, however we need the polyfills.

Further investigation resulted in noticing that requiring css-loader is where the error is coming from, so I moved our import '...application.scss' to above import 'babel-polyfill'… and that worked.

No idea why my working copy got busted, nor why it was working for the last week but suddenly not now (I had restarted Webpack multiple times in there so it wasn’t a hanging configuration). Seems to be a load order issue of some kind related to assets, at least for us.

In my case I also have error 😢 but I have webpack 3.11.0

Uncaught TypeError: Cannot read property 'call' of undefined
    at t (bootstrap d28002862bc097a50fc0:54)
    at Object.<anonymous> (common.6e1cfa22.js:35973)
    at t (bootstrap d28002862bc097a50fc0:54)
    at window.webpackJsonp (bootstrap d28002862bc097a50fc0:25)
    at common.6e1cfa22.js:1

HashedModuleIdsPlugin is enabled, and my CommonsChunkPlugins settings is

 new webpack.optimize.CommonsChunkPlugin({
        names: ['common', 'assets'],
        minChunks: Infinity,
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['editor'],
        async: true,
        chunks: ['common'],
        minChunks: module => {
          const editorRegexpModules = [
            /react-draft-wysiwyg/,
            /draft-js/,
            /html-to-draftjs/,
            /draftjs-to-html/,
            /dompurify/,
            /react-color/,
          ];

          const context = module.context;

          return (
            context &&
            context.indexOf('node_modules') >= 0 &&
            editorRegexpModules.some(rx => rx.test(context))
          );
        },
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['runtime'],
        async: true,
        children: true,
        minChunks: 5,
      }),

Entry:

entry: {
      common: [
        'react',
        'react-dom',
        'react-redux',
        'redux',
        'redux-thunk',
        //Editor
        'react-draft-wysiwyg',
        'draft-js',
        'html-to-draftjs',
        'draftjs-to-html',
        'dompurify',
        'react-color',
      ],
      assets: ['jquery', 'moment', PATHS.appAssetsJs],
      app: PATHS.appIndexJs,
    },

On picture you can see what moduleId is 0 image

I have reproduced it. I am using Angular-CLI version 1.6.5 in order to build very simple Angular app. I have attached .zip file with the project and instructions in README.md. Here is how you can reproduce the error:

The problem occurs when you import QuillModule from ngx-quill
into your app.module.ts. 
You could start with brand new "ng new call-error" 
then "npm install ngx-quill" and in app.module.ts simply
import it into angular module "imports" array. app.module.ts would look like:
---
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { QuillModule } from 'ngx-quill';

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    QuillModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
---

Perform "ng build --prod" and serve the result from "dist" folder.
The problem is reproduced with:
Angular-CLI version 1.6.5
ngx-quill version 2.0.4 
Angular version 5.2.1. 

Other versions:
Angular CLI: 1.6.5
Node: 9.3.0
OS: win32 x64
Angular: 5.2.1
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic

@angular/cdk: 5.1.0
@angular/cli: 1.6.5
@angular-devkit/build-optimizer: 0.0.41
@angular-devkit/core: 0.0.28
@angular-devkit/schematics: 0.0.51
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.5
@schematics/angular: 0.1.16
typescript: 2.6.2
webpack: 3.10.0

Sample package.json file:

{
  "name": "call-error-repro",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "core-js": "^2.4.1",
    "ngx-quill": "^2.0.4",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "1.6.5",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

Please see attached file for reproduction. It also contains webpack build in dist folder that causes the error.

Edit: Forgot to mention my observation - if I perform ng build --prod --sourcemaps the error disappears…

Edit 2: Forgot to mention also that if you switch off angular build optimizer, the error will disappear but the size of your bundle will increase - ng build --prod --build-optimizer=false

call-error-repro.zip

I’m was having same issue using ExtractCssChunks. Only working when the project was rebuilt. Resolved this using allChunks: true

new ExtractCssChunks({
  filename: 'templates/[name].css',
  allChunks: true
});

I was just running into this, for me it was the ModuleConcatenationPlugin plugin.

@TheLarkInn which version will fix this problem ?

I changed CommonsChunkPlugin.minChunks to Infinity, the problem is gone, but the vendors.js has nothing.

From DedupePlugin https://webpack.github.io/docs/list-of-plugins.html#dedupeplugin :

Note: Don’t use it in watch mode. Only for production builds.

I got it solved by removing it from my development config

Same here. Get this error when using the CommonsChunkPlugin with an optional minChunks function. Somehow it causes the main (entry) file inclusion as dependent one into the common (vendor.js in my case) chunk and then its removal after optimization (or somethign like) from so that it leads to the runtime error once absent module is called. Have no ideas why it happens but resolution for me is removing any conditions from the minChunks function that might accidentally specify the entry file name as a target to the commons chunks list. Then it works well.

Im having this issue also, it seems to be caused by the named chunks in the CommonsChunkPlugin.

new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            filename: 'common' + (options.production ? ".min" : "") + '.js',
            chunks: ['admin', 'angular', 'app'],
            minChunks: 2
        })

If I comment out the chunks line, it works as expected

Edit: I was eventually able to fix the problem by removing the angular chunk (which didnt need to be there) Still not 100% on the problem though.

Why is this closed? This is still an issue

I’m seeing the same issue with the latest webpack and optimization.splitChunks on.

Awesome, it works. https://webpack.js.org/configuration/optimization/#optimizationconcatenatemodules

I’m getting this change too for webpack v4.10.2. No code change, updated package lock and production is broken.

I was stuck with this using 1.13.2 and 1.14.0. It came up when I added a second instance of the CommonsChunkPlugin. Adding minChunks: 1 solved the issue. No idea why.

    new webpack.optimize.CommonsChunkPlugin({
      names: ['desktop/vendor', 'desktop/manifest'],
      filename: '[name].[hash].js',
      chunks: [
        'desktop/post-display',
        'desktop/post-list',
        'desktop/blog-display',
        'desktop/blog-list',
        'desktop/contact',
        'desktop/search'
      ],
      minChunks: 1 // Without this it doesn't work
    }),

    new webpack.optimize.CommonsChunkPlugin({
      names: ['mobile/vendor', 'mobile/manifest'],
      filename: '[name].[hash].js',
      chunks: [
        'mobile/post-display',
        'mobile/post-list',
        'mobile/blog-display',
        'mobile/blog-list',
        'mobile/contact',
        'mobile/search'
        ],
        minChunks: 1 // Without this it doesn't work
    }),

I have the same promble Uncaught TypeError: Cannot read property 'call' of undefined. I think the reason maybe if you use code spliting, webpack will generate a id for the chunk. Every build time, the chunk id maybe change, but if you don’t change the chunk file, this file’s chunkhash will not change, so the browser will use the cache first. This time, the another file which require the chunk by chunk id will get the error chunk id.

@sickboy Thanks a lot for the comment. We at @taskworld are experiencing this problem on production, and your comment helped me investigate the problem further.

I think I found the root problem:

We’re using long-term caching,

DedupePlugin replaces duplicated module with another module’s number, but that number isn’t used to hash the chunk.

Reproducing the problem

Version: webpack 1.14.0
  • webpack.config.js builds src/main1.js and src/main2.js into separate build folders.

    const webpack = require('webpack')
    const plugins = [ new webpack.optimize.DedupePlugin() ]
    
    module.exports = [
      {
        entry: './src/main1.js',
        output: {
          path: __dirname + '/build/out1',
          filename: "output.[hash].bundle.js",
          chunkFilename: "[chunkhash].bundle.js"
        },
        plugins: plugins
      },
      {
        entry: './src/main2.js',
        output: {
          path: __dirname + '/build/out2',
          filename: "output.[hash].bundle.js",
          chunkFilename: "[chunkhash].bundle.js"
        },
        plugins: plugins
      }
    ]
    
  • src/a.js

    module.exports = 1
    
  • src/b.js

    module.exports = 2
    
  • src/c.js is a duplicate of src/a.js

    module.exports = 1
    
  • src/d.js is a duplicate of src/b.js

    module.exports = 2
    
  • src/main1.js

    require('./a')
    require('./a')
    require('./b')
    require.ensure([ ], function () {
      require('./c')
      require('./d')
    })
    
  • src/main2.js

    require('./b')
    require('./b')
    require('./a')
    require.ensure([ ], function () {
      require('./c')
      require('./d')
    })
    

The case of src/main1

In the case of main1, ./a is required before ./b, so:

  • ./a gets ID 1
  • ./b gets ID 2

When it gets built, the chunk file 8dd6ff7e4b0954b12f3f.bundle.js looks like this:

webpackJsonp([1],[
/* 0 */,
/* 1 */,
/* 2 */,
/* 3 */
/*!******************!*\
  !*** ./src/c.js ***!
  \******************/
1,
/* 4 */
/*!******************!*\
  !*** ./src/d.js ***!
  \******************/
2
]);

The case of src/main2

In the case of main1, ./b is required before ./a, so:

  • ./a gets ID 2
  • ./b gets ID 1

When it gets built, the chunk file 8dd6ff7e4b0954b12f3f.bundle.js looks like this:

webpackJsonp([1],[
/* 0 */,
/* 1 */,
/* 2 */,
/* 3 */
/*!******************!*\
  !*** ./src/c.js ***!
  \******************/
2,
/* 4 */
/*!******************!*\
  !*** ./src/d.js ***!
  \******************/
1
]);

The hash is the same as previous run, which breaks long-term caching.

Proposed solution

When replacing the module with another module’s ID, webpack should hash the module by another module’s ID instead of its content.

I faced this issue today. In my case, I had to change this syntax:

new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js')

into this:

new webpack.optimize.CommonsChunkPlugin({
  names: ['vendors', ],
  minChunks: 2,
})

@sickboy This problems happened to me with 2.1.0-beta20。When i debugged the source code in Chrome-devTools , I find this: image module 0 , 1 must be external jquery image Cannot read property ‘call’ of undefined I don’t want to remove the common chunks and use a single entrypoint…

I also had this issue.

I upgraded from 1.12.14 to 1.13.0 without relief.

I removed my use of CommonsChunkPlugin and was promptly relieved (thanks @stream7, @orrybaram, @hinell). However, my bundle sizes increased.

I put back the CommonsChunkPlugin and added cache: false. Was again relieved (thanks @janusch), but my build time had increased.

Then I realized I had two separate “webpack --watch” processes running on the source at the same time. Aha! That could mess with caching, couldn’t it?

Ceasing to “webpack --watch” twice relieved me of this issue. In my boneheaded case, I no longer needed cache: false and could safely use the CommonsChunkPlugin. Small bundles, fast builds: workflow restored.

follow step by step this solution for fix this problem, working with me using webpack 4

1.STEP ONE output: { library: ‘[name]’, umdNamedDefine: false }

optimization: { concatenateModules: false, providedExports: false, usedExports: false }

  1. STEP TWO remove symlink and caheWithContenxt

  2. STEP THREE remove react hot module or disable this for production

  3. STEP FOUR remove old project name in heroku, after remove old project create new project name

Still, have this problem. why issue closed?

try sudo ionic serve or in windows open shell as Administrator

this is beause of the “use strict” , in ES5, arguments.callee() and arguments.caller() are forbid , you can delete the file “.babelrc " ->” ‘modules’: false " , everything is OK.

the only thing i wanna know is how this problems happened

i am getting the same error. local it works fine but in prod it fails randomly.

my webpack.config.js seems like this

new CommonsChunkPlugin({ “name”: “inline”, “minChunks”: null }), new CommonsChunkPlugin({ “name”: “vendor”, “minChunks”: (module) => module.resource && module.resource.startsWith(nodeModules), “chunks”: [ “main” ] }),

pls help me where i need to make changes

I was experiencing this issue and unfortunately, none of the solutions above helped me.

I created the After Chunk Hash Plugin to alleviate the issue.

It essentially waits until all assets have been output, and then rehashes them based on their final contents - it’s a bit of a hack, but I’ve been using it in production for the last few months on a large scale build & site, and it’s been working great.

It works with:

  • Common Chunks Plugin
  • Manifest Chunking
  • manifest.json from Webpack Manifest Plugin (or similar plugins)
  • Webpack 1 and 2

Full info as to what it solved has been posted in the readme

Same issue here, but I found a fix!

First, I want to explain that I have a vendor entry that looks like this:

entry: {
    vendor: compact([
        'babel-polyfill',
        'react',
        isDev && 'webpack-hot-middleware/client'
    ]),
    ...moreEntries
},

Before (broken)

new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    chunks: ['all', 'entries', 'that', 'are', 'not', 'vendor'],
    minChunks: 9
}),
new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    chunks: ['common'],
    minChunks: isExternal
}),

My strategy has been to have a vendor.js file with all the node_modules and all the other common chunks go in a common.js file. Works great for a production build, but fails on the dev server with “Uncaught TypeError: Cannot read property ‘call’ of undefined”.

The moduleId is not found, probably because I picked any node_modules out of an existing common chunk.

After (fixed)

isDev && new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: 9
}),
!isDev && new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    chunks: ['all', 'entries', 'that', 'are', 'not', 'vendor'],
    minChunks: 9
}),
!isDev && new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    chunks: ['common'],
    minChunks: isExternal
}),

The solution was to treat the dev server differently and only do a vendor.js file that has not only all the node_modules, but also all the common chunks, all in one file.

Hope this helps someone!

just remove ‘new webpack.optimize.CommonsChunkPlugin’

I’m on 2.1.0-beta.25. I have tried all the tips above, and the only one that ‘works’, is to set minChunks to Infinity in the CommonsChunkPlugin. Removing DedupePlugin made no difference for me. I see in chrome that it is looking for module id 2, but as you can see from the array, that number is skipped.

image

When I run webpack --display-modules I get the same thing, nr 2 is missing 😃

image

I then created a stats.json file and analyzed it in https://webpack.github.io/analyse. Everything was fine.

When I search in stats.json I see that id:2 is jQuery , which I have defined as external.

image

Is there a change in how externals work in webpack 2? By the way, this partitcular problem - call undefined - disappears if i remove the externals section.

Thomas

Maybe it’s fixed… Please reopen if still an issue with 1.8.4

@apertureless I am using version 3. But version 4 also works if I remove the <style></style> tags from the components.

I had the same problem with this error message. I removed a empty style tag in my newly added component that cause the issue:

<style scoped>
</style>

After that it worked again!

Hi everyone,

I just fix this issue by using this webpack.mix.js configuration :

const mix = require(‘laravel-mix’); var webpack = require(‘webpack’); /* |--------------------------------------------------------------------------

Mix Asset Management
Mix provides a clean, fluent API for defining some Webpack build steps
for your Laravel application. By default, we are compiling the Sass
file for the application as well as bundling up all the JS files.
*/
mix.js(‘resources/js/app.js’, ‘public/js’)
// .extract([‘vue’])
// .sass(‘resources/sass/app.scss’, ‘public/css’)
.webpackConfig({
  output: {
  	publicPath: '/public/',
                   chunkFilename: '[id].chunk.[chunkhash].js'
  },

plugins: [ new webpack.IgnorePlugin(/^./locale$/, /moment$/) ] }) .version();

I’m using :

  1. Laravel 5.6
  2. laravel-mix ^4.1.2
  3. vue ^2.6.10

The point to change is at publicPath. By default chunkFilename will save the file at public folder on Laravel framework, as long as we are not put folder name before the chunkFilename. example : js/[id].chunk.[chunkhash].js will automatically save the file on public/js/ folder if we dont put any folder name before the chunkFilename, all the file will save on public folder on Laravel.

So laravel will find the generated chunkFilename from public folder. There is a different path between using laravel on our local PC and on the server

If we run Laravel on our local PC, we usually use command php artisan serve. And if we want to call a file inside public folder, we don’t need to put public on url when you call a file. example : http://localhost:8080/app.js

but at the server we need to put public folder. example : https://yoursite.com/public/app.js

That’s why i set publicPath: ‘/public/’ to tell the laravel that my chunkFilename generated inside public folder

I don’t need to downgrade my laravel-mix. Hope this help anyone that still have the problem

@apertureless I am using version 3. But version 4 also works if I remove the <style></style> tags from the components.

In my case, I was getting the error because I was attempting to import files already packaged by webpack for production but I didn’t package them properly. The “properly” part required that I specify:

library: 'someName', // Having a value here is important
libraryTarget: 'umd',

@strickland84 I think, in laravel’s webpack.mix.js :

mix.webpackConfig({
    output: {
        chunkFilename: '[id].chunk.[chunkhash].js',
    }
});

Or in webpack.config.js :

module.exports = {
  output: {
    chunkFilename: '[id].chunk.[chunkhash].js',
  }
};

But this didn’t work for me…

@nicolaelitvac thanks for the above - where did you set this config? Which file? Thanks

This happens to me a lot as well. I’m working on an Angular Monorepo with internally built angular libraries. When we make changes to the libraries, we use a --watch flag, which triggers an incremental build, then the main app does the same, every time the build either fails, or it succeeds, but any action aftewards results in this error until I restart the app (via webpack a la ng serve command)

EDIT: I’m happy to provide whatever details I can to resolve the issue, just need someone from the webpack team to let me know what they need from me and I will produce it for them.

change my minChunkSize fixed

It happened to me from nowhere. I was happily compiling styled Vue single file components. Now if the component has a <style> tag the compilation fails with this very error. Removing the style fixes the compilation.

after some tests I decided that my build breaks on config:

optimization: {
  splitChunks: {
    default: {
      chunks: 'all'
    }
  }
}

i simply stop the serving and npm start again this solves for me.

I believe that I might have found a reproduceable scenario to recreate this issue consistently. It occurs when 1 named entry point imports another named entry point. For example:

// webpack.config.js

config = {
  ...
  entry: {
    src: './src/index.js',
    Component: './src/components/Component.js'
  },
  ...
}

// src/index.js

import './src/components/Component'

// src/components/Component.js

const Component = () => 'Hello World'

export default Component

This scenario will cause the Component.js exported in a way that causes this error.

I just had the same issue of “call of undefine” … i was able to resolve it by downgrading to version 4.9.2 which is a more stable version… it worked… however … the issue returned when i added cacheGroups not set to default: false…

cacheGroups: { vendors: { test: /[\/]node_modules[\/]/, priority: -10 }

when it is set to default: false … the issue is gone…

I have just run into this using Webpack 4.12.0

For me it seems that it only exhibits itself when

  • I am using production mode (its nothing to do with the devtool, minimize or module ids, see below)
  • I have multiple entry points
  • One of the entry points is completely shared with another entry point (i.e. it contains no unique code, so the chunk that is output is literally just the runtime)

I tried production mode with devtool: 'eval', plugins: [new webpack.NamedModulesPlugin()] and optimization: {minimize: false} and it still failed so I’m confident its got nothing to do with the module naming/ids or minification.

The entry point which contains no unique code contains something like this in the runtime code deferredModules.push([null,9]); which is where the error seems to come from as the null value is obviously not an actual module id. It should be something like deferredModules.push([462,9]);

My workaround was to create an small shim file which doesn’t actually do anything but import the actual entry file and export it again. Then I set the entry point to this shim file. e.g.

import realEntryPoint from './realEntryPoint';
export realEntryPoint;

The root cause is what @gdi2290 said. Because “You must load the generated chunk before the entry point” CommonsChunkPlugin

In my case, I used [‘common’, ‘c1’, ‘c2’] in HtmlWebpackPlugin, I used

chunksSortMode: function (chunk1, chunk2) {
        return chunk1.id - chunk2.id
      },

I don’t know why it works before. So I change “chunk1.id - chunk2.id” to “chunk2.id - chunk1.id”, all chunks are in right order now! Problem fixed.

@WouterVanherck I only experienced the ‘call’ of undefined error as a result of upgrading to Webpack 4. The only other thing I did was make sure that the plugins I’d added to my Webpack configuration were upgraded to versions compatible with Webpack 4.

Looking at your stack trace and https://github.com/webpack/webpack/blob/master/lib/TemplatedPathPlugin.js it seems like you’re probably not on the latest version of that plugin. Just a guess though.

Removing CommonChunksPlugin worked for now

This was happening to me because I accidentally overwrote a bundle with the same name:

  1. Manually defined an entrypoint fooBar in my webpack.config
  2. Somewhere else in the project: import(/* webpackChunkName: "fooBar" */ "./index")

Changing it to import(/* webpackChunkName: "fooBarLazy" */ "./index") fixed my issue (as would removing the chunkname entirely).

I was still getting some issues in my production builds, however this workaround solved it for me: https://github.com/AnujRNair/webpack-after-chunk-hash-plugin After some small adjustments, it seems to work well for my situation. (See the open issues for my two adjustments).

Im also trying out https://github.com/adventure-yunfei/md5-hash-webpack-plugin as an alternative.

v2.2.0   =>  "webpack": "3.0.0"

"html-webpack-plugin": "^2.22.0",
"extract-text-webpack-plugin": "^2.1.2",

add

plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
]
Uncaught TypeError: Cannot read property 'call' of undefined

image

Uncaught TypeError: Cannot read property 'shape' of undefined

image

Ok I think I got it working. The issue always appears in webpack 2.3.0 and up, but (apparently) it works on version 2.2.0.

I’m only having this issue on Cloud9 IDE, by the way. On my local machine it works fine.

There’s nothing particular about my CommonChunkPlugin:

new webpack.optimize.CommonsChunkPlugin({
    name: ['aurelia']
})

Anything new I could try?

Which version fixes this issue? Still seeing this issue with Webpack 2.2.0

Edit: Turned out to be a caching issue

I’m going to tackle this right now, if anyone can provide a very small reproducible example, that would be excellent. I should have enough information to build test cases that should fail, but it would be extra helpful if possible 🙏

DedupePlugin broke our production build. After removing it, our build is fine. Webpack version is 2.1.0-beta.25, used in the context of react-boilerplate (https://github.com/mxstbr/react-boilerplate).

A “npm install react-boostrap” was enough to trigger the problem.

Removing dedupe plugin solved this for me as well. The problem started when I added NamedModulesPlugin. My project has three css imports and dedupe plus extract-text-plugin meant that the first two modules ended up like "./node_modules/typeface-alegreya/index.css": "./styles/zenburn.css" which apparently Webpack can’t follow when doing module resolution. I’m on Webpack 1.

I am not using HtmlWebpackPlugin and of all the suggestions, the one that worked was not to use the DedupePlugin.

Unfortunately this results into a significantly bigger bundle (in terms of size).

Any other ideas on how to resolve this?

@sokra Is this a “core” Webpack thing or something related to “the plugins”?

Apologies this was on accident.

When I first got this error I “fixed” it by removing the DedupePlugin but after a while it appeared again. Since I don’t use the HtmlWebpackPlugin I tried out a few different things and managed to work around it by removing the UglifyJsPlugin.

I just run into this bug; in my case, the problem was using pure ES6. As soon as I transpiled it with Babel, the problem went away. Just a note.

HI All

Just for information, I founf that this error it is a bit misleading, it is not a bug but the way how you build your common chunks. please refer to

this works for me

entry: {
    tradeReporting: './app/tradeReporting/main.ts',
    admin: './app/admin/main.ts',
    polyfills: './app/lib/polyfill.ts'        
},
output: { path: './app/lib', filename: '[name]Bundle.js', chunkFilename: "[id].chunk.js" },
resolve: { extensions: ['', '.ts', '.js'] },
plugins: [         
     new webpack.optimize.CommonsChunkPlugin({ names: ["vendor", "polyfills"], minChunks: 2 }),

https://github.com/webpack/webpack/tree/master/examples/multiple-commons-chunks or https://github.com/webpack/webpack/tree/master/examples/common-chunk-and-vendor-chunk

Found a similar issue in our production builds. I could only reproduce it by setting NODE_ENV to “production”. Removing DedupePlugin from our webpack config file did the trick, but now our bundle sizes are bigger. Please fix!! I’d be more than happy to provide more info.

We’re using webpack@1.12.15

// Module can be created from a template
modules[moduleId] = (function(_m) {
    var args = _m.slice(1), templateId = _m[0];
    return function (a,b,c) {
        modules[templateId].apply(this, [a,b,c].concat(args));  // <<<  Uncaught TypeError: Cannot read property 'apply' of undefined
    };
}(_m));

@janusch where do you add that option, under CommonsChunkPlugin?

+1 Have same issue when run karma in watch mode. Workaround remove entry property of webpack config object in karma.conf.js

    delete webpackConf.entry;

Same problem here.

Quite difficult to understand exactly how to reproduce the problem, but it seems to happen more frequently when I edit a symlinked module or simply a module inside node_modules during a watch build.

v1.12.1

I’m facing this issue only when I use ExtractTextPlugin + SplitByPathPlugin (or split by name). It goes away if I remove either one of them.