Can't get external library with browserify and

2019-02-12 17:16发布

问题:

I have a headache on my hands. Here's my current setup:

  • bower to get vendor libraries (angular in this case)
  • gulp task to run browserify
  • debowerify to make the bower libraries compatible with browserify

App.js (before browserify):

'use strict';

var angular = require("angular");
var Routes = require("./routes");

angular.module('MyAngularApp')
  .config(Routes);

App.js (after browserify/in the bundle.js):

var angular = require("./../ext/angular/angular.js");
var Routes = require("./routes");

angular.module('MyAngularApp')
  .config(Routes);

So far so good, right? It seems like debowerify did it's job and replaced the angular with the relative path to the angular.js from bower.

But when I debug the bundle.js in the browser command line, after executing the first two require lines (for angular and Routes), angular is an empty obj, but Routes is exactly the correct function that I setup in the export.

Question: Why isn't angular being imported correctly using the require function?

I put this into my package.json to get the debowerify working:

  "browserify": {
    "transform": [
      "debowerify"
    ]
  },

回答1:

AngularJS doesn't support CommonJS at the moment, so var angular = require("angular") doesn't work. Instead of it, use just require('angular').

'use strict';

require('angular');
var Routes = require("./routes");

angular.module('MyAngularApp')
  .config(Routes);

The Angular object will be loaded globally and it'll be able to be accessed by other JS files, too.