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?
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!)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With