如何使用gulp构建JavaScript包?

时间:2014-04-04 23:57:34

标签: javascript amd commonjs gulp browserify

我想使用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
  7. 有供应商包括(1-2),本地包括(3-4)和捆绑文件(5-6)。

    供应商包含的只是与bowercomposer一起安装的第三方JavaScript库。它们可以是 CommonJS AMD 或只是一个普通的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处理此源文件并创建最终分发文件(bundle),确保所有依赖项(包括)在一个文件中合并在一起。所以我可以从我的HTML中包含 foo.js ,并且可以使用所有依赖项。

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

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

2 个答案:

答案 0 :(得分:5)

你提出的问题好像只有一个答案,但是没有。您尝试解决的问题是许多人以多种方式解决的问题,您已经确定了两个主要选项:AMD和CommonJS。还有其他方法,但考虑到你可能不熟悉Javascript依赖管理以及gulp,我建议选择相对简单的东西(即使这个主题本身并不简单)。

我认为最简单的路线可能是:

  • 使用CommonJS表达依赖关系
  • 使用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文件。

答案 1 :(得分:1)

有一个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
相关问题