如何处理非SPA使用的项目级捆绑?

我正在学习browserify,我正在尝试做两件基本的事情:

  1. 转换(通过填充)非CommonJS模块,便于使用和依赖性跟踪
  2. 捆绑项目特定的库

我发现了一个如何做到这一切的工作stream程,并通过Gulp实现了自动化。 这工作,并产生正确的输出,但我很好奇,如果它可以变得更简单。 似乎我必须在基于项目的包上重复大量的configuration。 这是一个工作的例子:

的package.json
无效的评论添加澄清

{ //project info and dependencies omitted //https://github.com/substack/node-browserify#browser-field "browser": { //tell browserify about some of my libraries and where they reside "jquery": "./bower_components/jquery/dist/jquery.js", "bootstrap": "./bower_components/bootstrap/dist/js/bootstrap.js" }, "browserify": { //https://github.com/substack/node-browserify#browserifytransform "transform": [ "browserify-shim" ] }, "browserify-shim": { //shim the modules defined above as needed "jquery": { "exports": "$" }, "bootstrap": { "depends": "jquery:$" } } } 

config.js
包含所有与任务pipe理器相关的configuration设置

 module.exports = { browserify: { // Enable source maps and leave un-ulgified debug: true, extensions: [], //represents a separate bundle per item bundleConfigs: [ { //I really want to refer to the bundles here made in the package.json but //if I do, the shim is never applied and the dependencies aren't included entries: ['/bundles/shared-bundle.js'], dest: '/dist/js', outputName: 'shared.js' } ] }, //... }; 

共享bundle.js
充当节点加载依赖关系的捆绑文件,在这一点上,垫片已被应用

 require('bootstrap'); 

browserify-task.js
包含browserify bundling gulp任务

 //module requires omitted gulp.task('browserify', function (callback) { var bundleQueue = config.bundleConfigs.length; var browserifyBundle = function (bundleConfig) { var bundler = browserify({ entries: bundleConfig.entries, extensions: config.extensions, debug: config.debug, }); var bundle = function () { return bundler.bundle() // Use vinyl-source-stream to make the stream gulp compatible .pipe(source(bundleConfig.outputName)) // Specify the output destination .pipe(gulp.dest(bundleConfig.dest)) .on('end', reportFinished); }; var reportFinished = function () { if (bundleQueue) { bundleQueue--; if (bundleQueue === 0) { // If queue is empty, tell gulp the task is complete callback(); } } }; return bundle(); }; config.bundleConfigs.forEach(browserifyBundle); }); 

config.js中,第一个bundleConfig项的entries是具有require()模块的文件的源,我想用package.json browser键中定义的模块的模块名replace它们。

config.js ,如果我将包configuration更改为:

  bundleConfigs: [ { entries: ['bootstrap'], dest: '/dist/js', outputName: 'shared.js' } ] 

并运行gulp任务,它将包含bootstrap.js,但它不运行填充转换。 jQuery并没有被包含在内。

这给我留下了几个问题:

  • 有没有更好的方法来绑定我的js在非SPA应用程序中使用(即,我是否以这种错误的方式进行)?
  • 如果没有,有没有办法确保在捆绑之前运行匀场转换,这样我可以在一个地方configuration捆绑configuration?

当然,你只需要告诉你的大嘴文件,它应该先填充。 看起来像从gulp文件中调用browserify时可以添加自己的shim对象。 看看这个例子

如果要在捆绑之前确保所有内容都已被刷新,请使用deps数组:“要在任务运行之前执行并完成的一组任务”。

它看起来像这样:

 gulp.task('shim', function() { // ... }); gulp.task('browserify', ['shim'], function(){ // ... });