我正在学习 browserify,我正在尝试用它做两件基本的事情:
- 转换(通过 shim)非 CommonJS 模块以实现易用性和依赖跟踪
- 捆绑项目特定的库
我找到了一个工作流程,说明如何使用 Gulp 完成所有这些工作并使其自动化。这可以工作并产生正确的输出,但是我很好奇它是否可以变得更简单。似乎我必须在基于项目的 bundle 上复制很多配置。这是工作示例:
gói.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
包含所有 task-runner 相关的配置设置
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
充当捆绑文件, Node 加载依赖项,此时已应用 shim
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
gọi lại();
}
}
};
return bundle();
};
config.bundleConfigs.forEach(browserifyBundle);
});
hiện hữu config.js
中,第一个 bundleConfig
项的 entries
是具有 require()
模块,我想用 package.json trình duyệt
键中定义的模块的模块名称替换它们。
hiện hữu config.js
中,如果我将捆绑配置更改为:
bundleConfigs: [
{
entries: ['bootstrap'],
dest: '/dist/js',
outputName: 'shared.js'
}
]
并运行 gulp 任务,它将包含 bootstrap.js 但它不运行 shim 转换。 jQuery 根本不包括在内。
这给我留下了几个问题:
- 有没有更好的方法来捆绑我的 js 以在非 SPA 应用程序中使用(即我是不是走错了路)?
- 如果没有,有没有办法确保在捆绑之前运行 shim 转换,以便我可以将捆绑配置放在一个地方?
当然,你只需要告诉你的 gulp 文件它应该首先填充。看起来您可以在从 gulp 文件调用 browserify 时添加自己的 shim
对象。查看 ví dụ này
如果您想在捆绑之前确保所有内容均已填充,请使用 deps
array: "在您的任务运行之前要执行和完成的任务数组。"
看起来像这样:
gulp.task('shim', function() {
// ...
});
gulp.task('browserify', ['shim'], function(){
// ...
});
Tôi là một lập trình viên xuất sắc, rất giỏi!