【问题标题】:Bundling underscore with jspm使用 jspm 捆绑下划线
【发布时间】:2016-01-05 03:41:15
【问题描述】:

我有一个需要下划线的模块:

import _ from "underscore"

var numbers = [1, 4, 6, 7, 9, 3, 22, 11, 54, 99, 100];
var evens = _.filter(numbers, x => x % 2 === 0);

document.getElementById('output').innerText = evens;

这在我的 gulp 任务中运行良好:

gulp.task('process-scripts', function(cb) {
    var builder = new Builder('Scripts', 'Scripts/config.js');
    builder.buildStatic('main.js', 'app/main.min.js', { minify: true });
    cb();
});

加上这个脚本标签:

<script src="/app/main.min.js"></script>

问题是,我想将下划线拉到它自己的脚本中。所以我将 gulp 任务更改为:

gulp.task('process-scripts', function(cb) {
    var builder = new Builder('Scripts', 'Scripts/config.js');
    builder.buildStatic('underscore', 'app/vendor.min.js', { minify: true });
    builder.buildStatic('main.js - underscore', 'app/main.min.js', { minify: true, globalDeps: {underscore: '_'} });
    cb();
});

这样做,我将下划线从主包中拉出并放入供应商包中。在 main.min.js 的底部,包创建了以下代码:

(function(factory) {
  factory(_);
});

我收到错误:“未捕获的 ReferenceError:_ 未定义”

我用 jQuery 代替下划线尝试了同样的事情,它工作得很好。我在单步执行代码时注意到,当调用 main 底部的代码时,在 window 对象上找到了$,因此没有错误。

如何让主模块识别供应商脚本中的下划线?

【问题讨论】:

  • 是否在 app/main.min.js 之前包含 app/vendor.min.js? app/vendor.min.js 是否单独将 _ 声明为全局变量?
  • 是的,app/vendor.min.js脚本标签在app/main.min.js之前vendor.min.js文件只有下划线,安装时用jspm install underscore在config.js 的映射对象为: ..., map: { "underscore": "npm:underscore@1.8.3" }, ...

标签: jspm systemjs


【解决方案1】:

如果您为 npm:underscore 创建一个自执行包,则不会将 _ 添加到窗口对象中。因此,您的主模块既不能通过import _ from 'underscore' 也不能通过window._ 访问。

如果您想将您的应用程序捆绑在单独的模块中,您应该只使用 builder.bundle() 创建捆绑包,而不是自动执行捆绑包。这样,您必须使用 system.js 来加载脚本,但您将能够访问应用模块中的下划线包。

例如:

System.import('app/vendor').then(() => {
   System.import('app/main');
});

【讨论】:

  • 知道为什么_ 不会被添加到窗口对象吗? jQuery 的 $ 似乎添加得很好。与下划线相比,它与jQuery的打包方式有关吗?
  • 是的。当您查看源代码时,您会看到 jquery 在浏览器环境中加载时被添加到窗口中:if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } 还有一个讨论为什么 jquery 这样做(github.com/jquery/jquery/pull/557)。下划线只是导出_。所以必须明确导入。
猜你喜欢
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
相关资源
最近更新 更多