如何使用grunt-run执行npm脚本?

Vis*_*ati 5 node.js npm gruntjs reactjs jestjs

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

  "scripts": {
    "test-jest": "jest",
    "jest-coverage": "jest --coverage"
  },
  "jest": {
    "testEnvironment": "jsdom"
  },
Run Code Online (Sandbox Code Playgroud)

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

    run: {
        options: {
          // Task-specific options go here.
        },
        your_target: {
          cmd: 'node'
        }
      }
Run Code Online (Sandbox Code Playgroud)

Rob*_*obC 13

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

  1. 设置cmdto 的值npm.
  2. 设置runtest-jestargs数组中.

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' ]);

};
Run Code Online (Sandbox Code Playgroud)

运行

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

注意:向Array 添加--silent(或者它的简写等效-s)args只会有助于避免额外的npm日志到控制台.


编辑:

跨平台

运行时,使用grunt-run上面显示的解决方案在Windows操作系统上失败cmd.exe.抛出以下错误:

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' ]);

};
Run Code Online (Sandbox Code Playgroud)

笔记

  1. grunt-shell需要load-grunt-tasks来加载Task而不是典型的grunt.loadNpmTasks(...),所以你也需要安装它:

npm i -D load-grunt-tasks

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

npm i -D grunt-shell@1.3.0


编辑2

grunt-run如果您使用exec密钥而不是cmdargs键,似乎在Windows上工作...

出于跨平台的目的......我发现有必要使用exec密钥将该命令指定为单个字符串,具体如下:

如果要将命令指定为单个字符串,对于在一个任务中指定多个命令很有用,请使用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' ]);

};
Run Code Online (Sandbox Code Playgroud)