2

我正在尝试在 Laravel 5.2 上使用 Elixir 和 Browserify Shim 设置 Browserify,以便在我的 JavaScript 文件中使用 Gulp,但到目前为止我运气不佳。这应该很简单,但事实并非如此。

这是我的package.json

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8"
  },
  "dependencies": {
    "bootstrap-sass": "^3.0.0",
    "browserify-shim": "^3.8.12",
    "jquery": "^2.2.0",
    "jquery-ui": "^1.10.5",
    "laravel-elixir": "^4.0.0"
  },
  "browser": {
    "app": "./resources/assets/js/app.js",
    "utils": "./resources/assets/js/utils.js",
  },
  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browserify-shim": {
    "app": {
      "depends": [
        "jquery:$",
        "utils:Utils"
      ]
    },
    "utils": {
      "depends": [
        "jquery:$"
      ]
    },
  }
}

gulpfile.js

var elixir = require('laravel-elixir');

elixir(function (mix) {
    mix.browserify('main.js', './public/js/bundle.js');
});

入口脚本main.js如下所示:

var $ = require('jquery');
var Utils = require('utils');
var App = require('app');

应用程序.js

var App = {
     init: function(){
         console.log(Utils);
         Utils.doSomething();
     }
    //other methods
};

简而言之:Utils依赖于$,而App依赖于$Utils

当我从终端点击 gulp 时,会正确创建 bundle.js。所有脚本都包含在 Browserify 代码中(如预期的那样)。每个脚本都包含所有依赖项,就像我在 package.json 中配置的那样,所以这部分看起来也不错。

问题是我包含的所有依赖项都是空对象。例如,app.js 中的 Utils 是空的,当我尝试调用它的方法“doSomething”时出现错误。控制台日志打印出一个空对象“ {} ”而不是真实对象。唯一正确包含的脚本是 jQuery,它不是一个空对象。

这里有什么问题?我是否需要在我的 JS 文件或配置中进行一些更改才能使其正常工作?看起来我非常接近解决方案,但它仍然不起作用,我根本无法使用它。

4

2 回答 2

2

直接使用 browserify-shim 属性中的“exports”是最简单的解决方案:

"browserify-shim": {
    "app": {
      "exports": "App",
      "depends": [
        "jquery:$",
        "utils:Utils"
      ]
    },
    "utils": {
      "exports": "Utils",
      "depends": [
        "jquery:$"
      ]
    },
  }
于 2016-02-01T13:22:14.187 回答
1

Take a look at this repo which I believe shows the fixed version of your app. The issue is that your app.js and utils.js modules aren't exporting anything to their respective require calls. One option is to add a line like:

module.exports = App;

to the bottom of your app.js file, and the equivalent to the bottom of your utils.js file. You'll see if you test the repo that badapp doesn't have this line and produces the exact behavior you're describing.

See this answer for an explanation of the issue.

于 2016-02-01T12:57:12.233 回答