我正在学习Browserify,并尝试用它完成两个基本任务:
1.通过shim转换非CommonJS模块,以便于使用和跟踪依赖关系 2.打包项目特定的库
我已经找到了一个可行的方法来完成所有这些,并使用Gulp进行自动化。这个方法可以工作并生成正确的输出,但是我想知道它是否可以更简单。似乎我必须在基于项目的捆绑包上重复很多配置。以下是一个工作示例: package.json (为了澄清而添加的无效注释)
1.通过shim转换非CommonJS模块,以便于使用和跟踪依赖关系 2.打包项目特定的库
我已经找到了一个可行的方法来完成所有这些,并使用Gulp进行自动化。这个方法可以工作并生成正确的输出,但是我想知道它是否可以更简单。似乎我必须在基于项目的捆绑包上重复很多配置。以下是一个工作示例: 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是一个捆绑文件,在这个文件中,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
callback();
}
}
};
return bundle();
};
config.bundleConfigs.forEach(browserifyBundle);
});
在 config.js
中,第一个 bundleConfig
的 entries
是指向一个文件的源代码,该文件中包含 require()
模块,我想将这些模块名称替换为在 package.json
文件的 browser
键中定义的模块名称。
如果我更改 bundle 配置为:
bundleConfigs: [
{
entries: ['bootstrap'],
dest: '/dist/js',
outputName: 'shared.js'
}
]
运行gulp任务时,它会包含bootstrap.js,但不会运行shim变换。jquery根本没有被包含。
这让我有几个问题:
- 有没有更好的方式捆绑我的js以用于非SPA应用程序(也就是说,我走错了吗)?
- 如果没有,是否有一种方法可以确保在捆绑之前运行shim变换,以便我可以在一个地方设置我的捆绑配置?
browser
条目时它就不起作用了。它能够看到主包(例如示例中的bootstrap),但它无法看到其shimmed依赖项jquery。 - Carrie Kendall