webpack / webpack

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
https://webpack.js.org
MIT License
64.21k stars 8.72k forks source link

Uncaught TypeError: Cannot read property 'call' of undefined #959

Closed kfancy closed 7 years ago

kfancy commented 9 years ago

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")
    ]
};
sokra commented 9 years ago

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

sokra commented 9 years ago

Maybe it's fixed... Please reopen if still an issue with 1.8.4

kfancy commented 9 years ago

It is really an incorrect bundle/chunk, I've flushed the browser to make sure of that. Essentially, the module trying to be required is 100% missing on an incremental watch build. Doesn't happen all the time.

For instance, using reactjs key mirror, on a list of constants, I'd require('react/lib/keyMirror'). On first build, no problem. On watch build, keyMirror module is completely missing from the file where it used to be.

makedonian commented 9 years ago

I'm still having this issue with 1.8.4. Pretty much the same setup as @kfancy, except my loader is jsx-loader?harmony

Worth mentioning is that it started happening after upgrading to react 0.13.1. I was porting code from 0.12 and didn't have issues even with webpack 1.7.2. Upgraded react, started having the issue, upgraded webpack to 1.8.4, and the issue still persist. I even removed the CommonsChunckPlugin to see if that would fix the problem, but no luck with that either.

I'm also getting random errors like Uncaught Error: Cannot find module "classnames" every now and then, only when running --watch.

DanielApt commented 8 years ago

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.

DanielApt commented 8 years ago

It has something do with our entry points:

We have issues when we use:

context: __dirname + '/project_name/static/js',
entry: {
        'static/dist/js/app': './components/app.js',
        'static/dist/js/log-in': './components/log-in.js',
        'static/dist/js/widget-a': './widgets/widget-a.js',
        'tests/testBundle': '../../tests/test.js', // removing this line fixes things
    },
    output: {
        path: __dirname + '/project_name',
        filename: '[name].js',
        sourceMapFileName: '[file].map'
    },

When removing testBundle things work nicely. Strangely enough the bundle throwing the error is actually app.js

PS: Sorry for the strange file system. We should address this once we have the chance.

DanielApt commented 8 years ago

@sokra could you re-open this issue?

sokra commented 8 years ago

Could you try upgrading to the lasted version?

DanielApt commented 8 years ago

Done. Still an issue.

jeffutter commented 8 years ago

I seem to be having this issue as well. It has been happening for the past few days, not sure if it was a webpack change or a code change that caused this. Let me know if I can help provide any info to track it down.

Cap32 commented 8 years ago

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

fxmaxvl commented 8 years ago

Is there any progress on this issue?

owais commented 8 years ago

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.

allantatter commented 8 years ago

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

jinroh commented 8 years ago

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

Jokcy commented 8 years ago

maybe you have some module in umd factory like this:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        /* AMD. Register as an anonymous module. */
        define(['require', 'exports'], factory);
    } else if (typeof exports === 'object') {
        /* CommonJS */
        factory(require, exports);
    } else {
        /* Browser globals - dangerous */
        factory(function(moduleName) { return root[moduleName]; }, root);
    }
}(this, function (require, exports) {
    var _ = require("lodash");
}))

maybe umd-require-webpack-plugin will help

eddywashere commented 8 years ago

@Jokcy how exactly do you use that plugin with webpack?

stream7 commented 8 years ago

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

zbyte64 commented 8 years ago

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);
maksimr commented 8 years ago

+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;
tomek-he-him commented 8 years ago

I have the same problem since I’ve symlinked my node_modules/ folder of a package to the root node_modules/ in a monorepo.

To reproduce:

git clone git@github.com:parametric-svg/- parametric-svg
cd parametric-svg
git checkout b5a6259b921a48cdef4c010c03ebc56fb593ea01
npm install
cd packages/parse
npm run browser-test
joefiorini commented 8 years ago

We're seeing this too in our app.

Uncaught TypeError: Cannot read property 'setPrototypeOf' of undefined(anonymous function) 

@ set-prototype-of.js:1__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ application.bundle.js:25900__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ inherits.js:5__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ Dock.js:3__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ index.js:7__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ DockMonitor.js:19__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ index.js:5__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ Pagination.component.js:17__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71createStore @ createStore.js:18(anonymous function) @ index.js:10__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ numberFormatInputs.js:25__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71webpackContext @ src Rails.js$:7(anonymous function) @ application.js:46(anonymous function) @ application.js:43__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71(anonymous function) @ application.bundle.js:5__webpack_require__ @ bootstrap 8aa52402241fffbcfe8b:71webpackJsonpCallback @ bootstrap 8aa52402241fffbcfe8b:42(anonymous function) @ application.bundle.js:1
VM62167:1 Uncaught ReferenceError: railsExports is not defined(anonymous function) @ VM62167:1window.ReactRailsUJS.mountComponents @ vendor.sprockets.js:1655(anonymous function) @ vendor.sprockets.js:1709fire @ jquery.js:3099self.fireWith @ jquery.js:3211jQuery.extend.ready @ jquery.js:3417completed @ jquery.js:3433

Occassionally it's also cannot read property apply of undefined. The culprit is typically a missing dependency from core-js. In the digging I did, I found that the missing file was included by react-dock which uses the static keyword from babel's es7 support. Could be a red herring, but our app only declares support for es6, so I'm wondering if maybe on an incremental rebuild it's not rebuilding react-dock (or anything else using es7-specific code from core-js) and therefore rebuilds the core-js dep with only things needed for es6 support.

Obviously this is only a hunch. I'm at a loss as to how to prove this. It happens sporadically, but probably a couple times per hour. It's also hard to tell if it's a problem with webpack, babel-loader, react-dock (not very likely) or something else.

To determine the above, I set the debugger to stop on uncaught exceptions and followed the stack trace down to where react-dock was calling setPrototypeOf.

Is anyone experiencing the issue in the same way I am? Or is this just different for everyone?

kawing-chiu commented 8 years ago

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
nnur commented 8 years ago

Hey, I'm getting this issue when I try to require textAngular and textAngular-santize. Any ideas on how I can get around it would be much appreciated!

jeremysuriel commented 8 years ago

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

bradbirnbaum commented 8 years ago

I had the same error and it was resolved be removing the DeDupePlugin - it would be great to get a fix please

orrybaram commented 8 years ago

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.

princed commented 8 years ago

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

benadamstyles commented 8 years ago

@princed The above link should be https://gitter.im/webpack/webpack/archives/2015/02/03

princed commented 8 years ago

@Leeds-eBooks Looks like it depends on time zone (:

benadamstyles commented 8 years ago

@princed So it does. Seems a strange decision to do it that way, for this very reason!

Jokcy commented 8 years ago

@eddywashere it seems like I get the email notification today? It's easy to use it, just new it in your webpack.config.js

And it's code is very simple, I believe you will understand it after 10m reading

bayov commented 8 years ago

Also happening to me when using webpack@2.0.5-beta. The error disappears when I remove DedupePlugin.

hinell commented 8 years ago

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.

dbismut commented 8 years ago

I don't know if this helps, but react-helmet made the DedupePlugin fail with the same error. Removing react-helmet from one of the chunks made the error disappear. And symmetrically, keeping react-helmet and removing the DedupePlugin also made the error disappear.

StephanBijzitter commented 8 years ago

Just started having this issue too...

node -v
v5.5.0

npm -v
3.3.12

webpack -v
1.12.14

Plugins used: CommonsChunkPlugin, uglifyJsPlugin. Loaders used: Babel

Tried removing the minChunks option as suggested above, but had no effect.

@joefiorini We also use ES7 (although we do it ourselves, and it isn't imposed on us by a library), perhaps our issues could be highly related. However, the project worked before (with the static keyword) and just suddenly started having issues.

Note that we use pure JS (aside from jQuery...), so React is not the issue in our case. I guess it is related to ES7, but yeah... what will you do about it...

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

module.exports = {
    devtool: 'source-map',

    entry: {
        <redacted>: path.resolve(__dirname, '../src/js/module/<redacted>/'),
        <redacted2>: path.resolve(__dirname, '../src/js/module/<redacted2>/')
    },

    output: {
        filename: '[name].min.js',
        path: path.resolve(__dirname, '../app/webroot/js/bin')
    },

    plugin: {
        commonsChunk: new webpack.optimize.CommonsChunkPlugin({
            name: 'common'
        }),

        uglifyJsPlugin: new webpack.optimize.UglifyJsPlugin()
    },

    resolve: {
        extensions: ['', '.js', '.es6', '.es7']
    },

    module: {
        loaders: [{
            cacheable: true,
            test: /\.es\d{1}$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query: {
                presets: ['es2015'],
                cacheDirectory: true
            }
        }]
    }
};
ivan-kleshnin commented 8 years ago

Got this error when replaced

export default {
  foo: foo
}

/////

import {foo} from "foo"

with semantically equivalent

export default function foo() {...}

/////

import foo from "foo"

in one particular file. Something magical happens because the same switch in other modules went without any problem.

janusch commented 8 years ago

@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!

likezero commented 8 years ago

Please fix the issue~

janusch commented 8 years ago

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

kamil-kielczewski commented 8 years ago

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

foffer commented 8 years ago

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

airwin commented 8 years ago

Remove the DedupePlugin and all work right (;

janusch commented 8 years ago

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

inv8der commented 8 years ago

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 commented 8 years ago

I just updated my app to use webpack@1.13.0 and cannot re-create this issue anymore, yay!!!

If a few others could confirm that it is working for them as well we might be able to close this issue.

Thanks @sokra for the 1.13.0 release. It is a pleasure again to have webpack in the toolchain!

kellyrmilligan commented 8 years ago

I just upgraded, with dedupe plugin running it is still causing an issue.

kellyrmilligan commented 8 years ago
screen shot 2016-04-18 at 10 01 23 am
jomido commented 8 years ago

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.

ghost commented 8 years ago

vendors.js:1Uncaught TypeError: Cannot read property 'apply' of undefined

I am getting the above error.

Below I have provided the config:

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var VendorChunkPlugin = require('webpack-vendor-chunk-plugin');

module.exports = {
  'devtool': 'eval-source-map',

  'entry': {
    'vendor': [
      'react',
      'react-dom',
      'react-router',
      'react-redux',
      'redux-thunk',
      'react-bootstrap',
      'redux',
      'redux-form',
      'axios'
    ],
    'app':  __dirname + '/src/main.js'
  },
  'output': {
    'path': __dirname + '/build',
    'publicPath': '/',
    'chunkFilename': '[id].[name].chunk.js',
    'filename': '[name].[hash].js'
  },

  'module': {
    'loaders': [
      // JSX and JS transpilation using babel
      {
        'test': [/\.js$/, /\.jsx$/],
        'exclude': /(node_modules|bower_components)/,
        'loader': 'babel'
      },
      // SASS modularization using style, css and postcss sass loader
      {
        'test': [/\.css$/, /\.scss$/],
        'loader': 'style!css!sass'
      },
      // Font path loader
      {
        'test': /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        'loader': 'file-loader?name=fonts/[name].[ext]'
      },
      // Image path loader
      {
        'test': /\.(jpe?g|png|gif|svg)$/i,
        'loaders': [
          'url-loader?limit=15000&name=images/[name].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      }
    ],
  },

  'sassLoader': {
    'includePaths': [
      path.resolve(__dirname, 'src/components/'),
      path.resolve(__dirname, 'src/components/common/assets/')
    ]
  },

  'resolve': {
    'root': [
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'src/components/common/assets/'),
      path.resolve(__dirname, 'src/components/common/'),
      path.resolve(__dirname, 'node_modules')
    ],
    'extensions': ['', '.js', '.jsx', '.scss'],
  },

  'plugins': [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.BannerPlugin("App has been developed by PRDXN."),
    new HtmlWebpackPlugin({
      'template': __dirname + '/src/index.tmpl.html'
    }),
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendors.js', Infinity),
    new VendorChunkPlugin('vendor'),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      'minimize': true,
      'screw-ie8': true,
      'mangle': false,
      'compress': {
        'warnings': false
      },
      'output': {
        'comments': false,
        'semicolons': true,
      }
    }),
    new webpack.optimize.DedupePlugin()
  ],

  'devServer': {
    'contentBase': './build',
    'host': '0.0.0.0',
    'https': true,
    'colors': true,
    'compress': true,
    'hot': true,
    'historyApiFallback': true,
    'inline': true,
    // Display only errors to reduce the amount of output.
    'stats': 'errors-only',
  }
};

This is how I start webpack build process:

"start": "rm -rf build/ && rm -rf dist/ && webpack && webpack-dev-server --progress --colors"