【问题标题】:How to use gulp to build JavaScript bundles?如何使用 gulp 构建 JavaScript 包?
【发布时间】:2014-05-17 11:32:47
【问题描述】:

我想使用 gulp 构建 JavaScript 文件包。

例如,我的项目中有以下结构:

  1. /vendor/vendor1/vendor1.js
  2. /vendor/vendor2/vendor2.js
  3. /js/includes/include1.js
  4. /js/includes/include2.js
  5. /js/bundle1.js
  6. /js/bundle2.js

有供应商包含 (1-2)、本地包含 (3-4) 和捆绑文件 (5-6)。

供应商包含的只是使用bowercomposer 安装的第三方JavaScript 库。它们可以是 CommonJSAMD 或只是一个普通的 jQuery 插件。

我想在捆绑文件中指定依赖项,如下所示:

/js/bundle1.js

(function() {

    // Vendor includes.
    include('vendor1');
    include('vendor2');

    // Local includes.
    include('includes/include1.js');
    include('includes/include2.js');

    // Some code here.

})();

我希望gulp 处理此源文件并创建一个最终分发文件(捆绑包),以确保所有依赖项(包含)都合并到一个文件中。所以我可以在我的 HTML 中包含 foo.js 并且所有依赖项都可以使用。

我希望有一个清晰而健壮的系统来管理项目内部的所有依赖项并构建分发文件。

  • 我怎样才能做到这一点?
  • 我自己的脚本应该使用什么格式(AMD、CommonJS、其他)?
  • 如何在源包文件中指定依赖项?
  • 如何构建分发?

【问题讨论】:

  • 对 2020 年问题的补充附录:现在原生 Chrome 支持 ES6 模块怎么样?火狐/边缘呢? Chrome 或 Firefox 插件/注入脚本呢?如果我们只针对最新版本的 Chrome 和同时支持旧版浏览器,我们的需求会发生变化吗?

标签: javascript amd commonjs gulp browserify


【解决方案1】:

您提出的问题好像只有一个答案,但实际上没有。您尝试解决的问题是许多人以多种不同方式解决的问题,并且您已经确定了两个主要选项:AMD 和 CommonJS。还有其他方法,但鉴于您可能不熟悉 Javascript 依赖管理以及 gulp,我建议您使用相对简单的方法(尽管这个主题本质上并不简单)。

我认为对你来说最简单的路线可能是:

  • 使用 CommonJS 表达依赖关系
  • 使用 browserify 将它们解析成包
  • 在 browserify 中,使用“UMD”方法,以便您获得一个适用于使用 AMD 或 CommonJS 或不使用这些依赖管理系统的应用程序的包

gulp 中运行 browserify 的语句可能类似于:

var browserify = require('gulp-browserify');
gulp.src('bundles/bundle1.js', {read: false})
  .pipe(browserify({
    'standalone': true
  })
  .pipe(rename('bundle1Output.js'))
  .pipe(gulp.dest('dist'));

这应该会给你一个 dist/bundle1Output.js 文件。

【讨论】:

  • 感谢您的回答!您能否提供可以与此配置一起使用的 bundle.js 示例?
  • Browserify 将期望您的 bundle1.js 文件指定您的依赖项。这已涵盖here
【解决方案2】:

为此有一个 gulp 插件:

https://www.npmjs.com/package/gulp-include

它应该做你想做的事,除了在你的包文件中而不是这个:

    (function() {

        // Vendor includes.
        include('vendor1');
        include('vendor2');

        // Local includes.
        include('includes/include1.js');
        include('includes/include2.js');

        // Some code here.

    })();

你必须写:

    //=require vendor1/**/*.js
    //=require vendor2/**/*.js

    //=require includes/include1.js
    //=require includes/include2.js

    // Some code here

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多