Empty object require angular browserify

我们两清 提交于 2019-12-10 07:34:10

问题


I m facing a problem when I try to use bowserify, angularjs and coffeescript.

In fact, when I try to require('angular'), I get an empty object :

angular = require('angular')
console.log angular ## return an empty object {}

configuration = require('../../config/config') 
console.log configuration ## returns my fully config file correctly

I dont know why it doesn't work properly in this case :-/. This is my package.json where I put the my personnal angular dependencies :

{
    "dependencies": {
        "gulp": "*",
        "gulp-browserify": "*",
        "coffeeify": "*",
        "gulp-concat": "*"
    },
    "browser": {
        "angular": "./app/core/angular-libs/angular.min.js",
        "angular-route": "./app/core/angular-libs/angular-route.min.js",
        "angular-animate": "./app/core/angular-libs/angular-animate.min.js"
    }
}

And this is my gulp file, that generates my bundle.js in dest folder :

var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');

gulp.task('scripts', function () {
    return gulp.src('app/**/*.coffee', { read: false })
        .pipe(browserify({ transform: ['coffeeify'], extensions: ['.coffee'] }))
        .pipe(concat('bundle.js'))
        .pipe(gulp.dest('./dest/'));
});

gulp.task('default', function () {
    gulp.run('scripts');
});

Can you help me ? :-/

Thanks for advance


回答1:


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

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

require('angular')

This will attach angular to the global object.

UPDATE: As of Angular 1.3.14, require('angular') now returns the angular object.




回答2:


You could also try browserify-shim to link the angular object to module.exports.

npm install -save-dev browserify-shim

I managed to get angular working with the following configuration in package.json:

{
    "browser": {
        "angular": "./node_modules/angular/angular.js"
    },
    "browserify-shim": {
        "angular": "angular"
    },
    "browserify": {
        "transform": [ "browserify-shim" ]
    }
}

This gets around the issue of making angular a global object, also. It (the angular variable) may stay an object stored in a global variable of the same name, but the reference will always be correct if someone overwrites the global variable.



来源:https://stackoverflow.com/questions/26216887/empty-object-require-angular-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!