簡體   English   中英

從 gulp 任務運行 npm 腳本

[英]Run a npm script from gulp task

如何從 gulp 任務內部運行 npm 腳本命令?

包.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());
});

我想這樣做是因為運行npm run tsc不會給我任何錯誤,但是如果我使用gulp-typescript來編譯.ts那么我會得到一堆錯誤。

您可以使用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

或者使用外殼

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已被列入黑名單,您可以在此處了解原因

另一種選擇是設置webpack

在這個簡單的事情上浪費了大約 1 個小時,尋找一個完整的答案,所以在這里添加另一個:

如果您的問題僅在打字稿 (tsc) 上,請參閱https://stackoverflow.com/a/36633318/984471
否則,請參閱下面的通用答案。

問題標題是通用的,所以下面先給出一個通用的例子,然后是答案。

通用示例:

  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 ,它將打印yay! cmd1 command is run. yay! cmd1 command is run. 每次 js 文件之一更改時。

對於這個問題:作為另一個例子:

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();

希望有幫助。

您可以嘗試使用 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());

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM