Max Koretskyi
Max Koretskyi

Reputation: 105497

why require("angular") returns an empty object

I've configured webpack like this:

resolve: {
    alias: {
        angular: path.join(__dirname, './node_modules/angular/angular.js')
    }
},

and in my file I require angular like this:

var angular = require("angular");

But for some reason an empty object is returned, why?

Upvotes: 10

Views: 1532

Answers (4)

Motin
Motin

Reputation: 5053

The other answers are not providing a working solution. It is true that Angular 1 is not working nicely with webpack out-of-the-box (see https://github.com/webpack/webpack/issues/2049), but it can be loaded with a shim. Try this webpack loader config:

module: {
    loaders: [
        /*
         * Necessary to be able to use angular 1 with webpack as explained in https://github.com/webpack/webpack/issues/2049
         */
        {
            test: require.resolve('angular'),
            loader: 'exports?window.angular'
        },
    ]
},
plugins: [
    new webpack.ProvidePlugin({
        'angular': 'angular',
    }),
],

This should initialize the angular object properly instead of the default action of setting it to an empty object (which does not have a property named module).

Upvotes: 4

Joe Clay
Joe Clay

Reputation: 35797

The other answers aren't quite accurate - it's true that the core angular.js file doesn't support CommonJS, but if you install it from NPM, a tiny wrapper file called index.js is provided. It's literally just two lines:

require('./angular'); // Runs angular.js, which attaches to the window object
module.exports = angular; // Exports the global variable

This allows you to use it in CommonJS environments like normal. So if you update your config like so, it should work:

resolve: {
    alias: {
        angular: path.join(__dirname, './node_modules/angular/index.js')
    }
},

(That said, this should be Webpack's default behaviour even if you don't alias angular, as index.js is marked as Angular's main file in its package.json - you probably can get away with just using no alias at all!)

Upvotes: 5

Rahul
Rahul

Reputation: 387

Angular 1 doesn't support CommonJS modules, so it 'exports' an empty object.

Instead, just require it (without assigning the result):

 require('angular')

Upvotes: 1

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Conceptual answer -

Angular 1.x does not support CommonJS modules that's why following approach of exporting yields an empty object:

var angular = require("angular");

So better omit the var angular part and just make use of require("angular");

Upvotes: 1

Related Questions