如何使用 g运行t-运行 执行 npm 脚本?

How to execute npm script using grunt-run?

我的 package.json 文件中有一个 npm 任务,执行 jest 测试如下:

  "scripts": {
    "test-jest": "jest",
    "jest-coverage": "jest --coverage"
  },
  "jest": {
    "testEnvironment": "jsdom"
  },

我想使用 g运行t 执行此任务 npm run test-jest。我为此安装了 g运行t-运行 并添加了 运行 任务,但是如何在那里调用这个 npm 任务?

    run: {
        options: {
          // Task-specific options go here.
        },
        your_target: {
          cmd: 'node'
        }
      }

配置您的 Gruntfile.js 类似于文档中显示的 example

  1. cmd 的值设置为 npm
  2. args 数组中设置 runtest-jest

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        cmd: 'npm',
        args: [
          'run',
          'test-jest',
          '--silent'
        ]
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};

运行

运行 $ grunt 通过 CLI 使用上面显示的配置将调用 npm run test-jest 命令。

注意:将 --silent(或者它的 shorthand 等效 -s)添加到 args 数组只是有助于避免将额外的 npm 日志记录到控制台。


编辑:

跨平台

当 运行 通过 cmd.exe 时,使用上面显示的 grunt-run 解决方案在 Windows OS 上失败。抛出以下错误:

Error: spawn npm ENOENT Warning: non-zero exit code -4058 Use --force to continue.

对于跨平台解决方案,请考虑安装和使用 grunt-shell 来调用 npm run test-jest

npm i -D grunt-shell

Gruntfile.js

module.exports = function (grunt) {

  require('load-grunt-tasks')(grunt); // <-- uses `load-grunt-tasks`

  grunt.initConfig({
    shell: {
      npm_test_jest: {
        command: 'npm run test-jest --silent',
      }
    }
  });

  grunt.registerTask('default', [ 'shell:npm_test_jest' ]);

};

备注

  1. grunt-shell 需要 load-grunt-tasks 来加载任务而不是典型的 grunt.loadNpmTasks(...),因此您也需要安装它:

npm i -D load-grunt-tasks

  1. 对于旧版本的 Windows 我必须安装旧版本的 grunt-shell,即版本 1.3.0,所以我建议安装较早的版本。

npm i -D grunt-shell@1.3.0


编辑 2

如果您使用 exec 键而不是 cmdargs 键,

grunt-run 似乎确实适用于 Windows ...

出于跨平台的目的...我发现有必要使用 exec 键将命令指定为单个字符串,如文档所述:

If you would like to specify your command as a single string, useful for specifying multiple commands in one task, use the exec: key

Gruntfile.js

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-run');

  grunt.initConfig({
    run: {
      options: {
        // ...
      },
      npm_test_jest: {
        exec: 'npm run test-jest --silent' // <-- use the exec key.
      }
    }
  });

  grunt.registerTask('default', [ 'run:npm_test_jest' ]);

};