我想要从lib.js
和lib/a.js
创建一个库lib/b.js
,并且可以使用client.js
从脚本var a = require('lib/a.js');
中使用它当我只在lib.js
之前包含已编译的client.js
库时,它才有用(因此,lib.js
必须声明一个知道require
的<{1}}函数< / p>
我想我必须使用lib/a.js
和external
,但我不确定这样做的正确方法
此外,是否可以使用Gulp文件自动为我的库中的文件夹创建所有别名?例如。为alias
目录中的所有文件创建别名?
答案 0 :(得分:14)
以下是一些有助于分别构建常见lib.js和client.js包的gulp任务。
请注意,在捆绑lib.js时,你必须告诉bandre()lib / * .js,你必须告诉b.external()捆绑客户端时将单独加载的库。 JS
var path = require('path');
var gulp = require('gulp');
var browserify = require('browserify');
var concat = require('gulp-concat');
var transform = require('vinyl-transform');
gulp.task('build-lib', function () {
// use `vinyl-transform` to wrap around the regular ReadableStream returned by b.bundle();
// so that we can use it down a vinyl pipeline as a vinyl file object.
// `vinyl-transform` takes care of creating both streaming and buffered vinyl file objects.
var browserified = transform(function(filename) {
// basename, for eg: 'a.js'
var basename = path.basename(filename);
// define the exposed name that your client.js would use to require();
// for eg: require('lib/a.js'); // -> exposed name should be 'lib/a.js'
var expose = 'lib/' + basename;
return browserify(filename)
.require(filename, { expose: expose})
.bundle();
});
return gulp.src(['./lib/*.js'])
.pipe(browserified)
.pipe(concat('lib.js'))
.pipe(gulp.dest('./dist'));
});
gulp.task('build-client', function () {
var browserified = transform(function(filename) {
// filename = './client.js'
// let browserify know that lib/a.js and and lib/b.js are external files
// and will be loaded externally (in your case, by loading the bundled lib.js
// for eg: <script src='dist/lib.js'>)
return browserify(filename)
.external('lib/a.js')
.external('lib/b.js')
.bundle();
});
return gulp.src(['./client.js'])
.pipe(browserified)
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['build-lib', 'build-client']);
答案 1 :(得分:-1)
您在寻找external requires吗?
要与gulp-browserify一起使用,请检查README
.on('prebundle', function(bundle) {
bundle.external('domready');
bundle.external('react');
})
也应该使用bundle.require。