运行 来自 gulp 任务的 npm 脚本

Run a npm script from gulp task

如何从 gulp 任务中 运行 npm 脚本命令?

package.json

"scripts": 
{
    "tsc": "tsc -w"
}

gulpfile.js

gulp.task('compile:app', function(){
  return gulp.src('src/**/*.ts')
    .pipe(/*npm run tsc*/)
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

我想这样做是因为 运行ning npm run tsc 不会给我任何错误,但是如果我使用 gulp-typescript 编译 .ts 那么我会得到一堆错误.

您可以尝试使用 childprecess 节点包或

来实现它

使用https://www.npmjs.com/package/gulp-run

var run = require('gulp-run');
gulp.task('compile:app', function(){
  return gulp.src(['src/**/*.js','src/**/*.map'])
    .pipe(run('npm run tsc'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());

});

您可以使用 gulp-typescript

获得等价物
var gulp = require('gulp');
var ts = require('gulp-typescript');

gulp.task('default', function () {
  var tsProject = ts.createProject('tsconfig.json');

  var result = tsProject.src().pipe(ts(tsProject));

  return result.js.pipe(gulp.dest('release'));
});

gulp.task('watch', ['default'], function() {
  gulp.watch('src/*.ts', ['default']);
});

然后在你的 package.json

"scripts": {
  "gulp": "gulp",
  "gulp-watch": "gulp watch"
}

然后运行

npm run gulp-watch

或者使用 shell

var gulp = require('gulp');
var shell = require('gulp-shell');

gulp.task('default', function () {
  return gulp.src('src/**/*.ts')
    .pipe(shell('npm run tsc'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

gulp-shell 已经 blacklisted you can see why here

另一种选择是设置 webpack

在这个简单的事情上浪费了大约 1 小时,寻找一个〜完整的答案,所以在这里添加另一个:

如果您的问题只是打字稿 (tsc),请参阅
否则,请参阅下面的通用答案。

题目比较笼统,所以下面先举个笼统的例子,再给出答案。

通用示例:

  1. 安装nodejs,如果没有,最好是LTS版本,从这里:https://nodejs.org/

  2. 下面安装:

    npm install --save-dev gulp gulp-run

  3. 文件 package.json 包含以下内容(其他内容可以存在):

{
      "name": "myproject",
      "scripts": {
          "cmd1": "echo \"yay! cmd1 command is run.\" && exit 1",
      }
}
  1. 创建一个包含以下内容的文件gulpfile.js
var gulp = require('gulp');
var run = require('gulp-run');

gulp.task('mywatchtask1', function () {
    // watch for javascript file (*.js) changes, in current directory (./)
    gulp.watch('./*.js', function () {

        // run an npm command called `test`, when above js file changes
        return run('npm run cmd1').exec();

        // uncomment below, and comment above, if you have problems
        // return run('echo Hello World').exec();
    });
});
  1. 运行 任务 mywatchtask1 使用 gulp?

    gulp mywatchtask1

现在,gulp正在监视当前目录下的js文件变化
如果发生任何变化,那么 npm 命令 cmd1 是 运行,它会在每次 js 文件之一发生变化时打印 yay! cmd1 command is run.

这道题:再举个例子:

a) package.json 会有

"tsc": "tsc -w",

而不是下面的:

"cmd1": "echo \"yay! cmd1 command is run.\" && exit 1",

b) 并且 gulpfile.js 将有:

return run('npm run tsc').exec();

而不是以下:

return run('npm run cmd1').exec();

希望对您有所帮助。