我有一个Gulp任务,它使用gulp-connect启动一个本地服务器,然后打开一个浏览器窗口,通过open与服务器交互。
代码如下所示:
const gulp = require('gulp');
const connect = require('gulp-connect');
const open = require('open');
const path = require('path');
// Create a local server for hosting the project.
// Responds to livereload commands so file changes don't require refreshing.
gulp.task('connect', (done) => {
const host = 'localhost';
const port = 8080;
connect.server({
host,
port,
// Needs to be path.resolve and not just './'
// https://github.com/AveVlad/gulp-connect/issues/54
root: path.resolve('./'),
livereload: true
});
// Open default browser to the compiled directory.
// Presumably useful since a connect server was just spun up for development.
open(`http://${host}:${port}/compiled/`);
done();
});目前,此功能仅支持在浏览器中打开compiled目录。我想扩展它,这样我就可以有选择地打开dist目录。
值得注意的是,我不是直接从命令行调用connect任务。相反,我正在运行其他任务,比如build,它想要向connect传达它想要打开dist目录的愿望:
gulp.task('build', (done) => {
// TODO: Have connect open to 'dist' and not 'compiled'
runSequence('compile', 'build', 'connect', done);
});我看到一些关于将命令行参数传递到Gulp任务的帖子,但我不认为这是相关的,因为我没有从命令行显式运行命令,但我可能是错误的。
动态配置此任务的正确方法是什么?
编辑:这是可行的,但感觉很老套:
const argv = require('yargs').argv;
const directoryName = argv._[0] === 'build' ? 'dist' : 'compiled';
open(`http://${host}:${port}/${directoryName}/`);发布于 2015-10-11 03:24:10
由于connect任务与gulp无关,因此您可以将其重构为一个函数,并从其他任务中调用该函数。
function connect(dir) {
const host = 'localhost';
const port = 8080;
connect.server({
host,
port,
root: path.resolve('./'),
livereload: true
});
open(`http://${host}:${port}/${dir}/`);
}
gulp.task('build', (done) => {
runSequence('compile', 'task2', 'task3', () => {
connect('dist');
done();
});
});这种解决方案的缺点是不能从命令行运行gulp connect。但是,如果您需要的话,创建一个使用上面的函数的connect任务将是微不足道的。
https://stackoverflow.com/questions/33057571
复制相似问题