我正在学习browserify,我正在尝试用它做两件基本的事情:
我找到了一个如何完成所有这些并使用Gulp自动化的工作流程。这工作并产生正确的输出,但我很好奇它是否可以变得更简单。好像我必须在基于项目的bundle上复制很多配置。以下是工作示例:
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
包含所有与任务运行器相关的配置设置
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'
}
]
},
//...
};
shared-bundle.js
充当捆绑文件,其中节点加载依赖项,此时已应用填充程序
require('bootstrap');
browserify-task.js
包含browserify捆绑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()
是包含browser
模块的文件的来源,我想要替换那些在package.json config.js
键中定义模块名称的那些。
在 bundleConfigs: [
{
entries: ['bootstrap'],
dest: '/dist/js',
outputName: 'shared.js'
}
]
中,如果我将捆绑配置更改为:
{{1}}
并运行gulp任务,它将包含bootstrap.js,但它不会运行填充程序转换。 jQuery根本没有包含在内。
这给我留下了几个问题:
答案 0 :(得分:1)
当然,你只需要告诉你的gulp文件它应该先垫片。从gulp文件调用browserify时,您似乎可以添加自己的shim
对象。查看this example
如果要在捆绑之前确保所有内容都已整理,请使用deps
数组:"在任务运行之前执行并完成的一系列任务。"
它看起来像这样:
gulp.task('shim', function() {
// ...
});
gulp.task('browserify', ['shim'], function(){
// ...
});