Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 547
Max Koretskyi Avatar asked Feb 23 '16 07:02

Max Koretskyi


2 Answers

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

like image 60
Joe Clay Avatar answered Nov 15 '22 15:11

Joe Clay


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

like image 40
Motin Avatar answered Nov 15 '22 14:11

Motin