3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gulp や mocha を使う時は yarn が便利

Last updated at Posted at 2017-04-04

以下の環境で確認

Terminal
$ node -v
v7.7.4
$ npm -v
4.4.4
$ yarn -v
yarn install v0.21.3
warning No license field
[1/4] 🔍  Resolving packages...
success Already up-to-date.
✨  Done in 1.76s.

yarn を使うと package.jsonscripts フィールドに余計なことを書かなくてよくなります。

例えば以下のようなファイル構成だった場合。

Terminal
$ tree .
.
├── gulpfile.js
├── package.json
├── src
│   └── calc.js
└── test
    └── calc-test.js
src/calc.js
function add(a, b) {
    return a + b;
}

function multiply(a, b) {
    return a * b;
}

module.exports = {add, multiply};
test/calc-test.js
var assert = require("assert");
var calc = require("../src-js/calc.js");

describe("calc", function() {
    it("add", function() {
        assert.equal(4, calc.add(1, 3));
    });

    it("multiply", function() {
        assert.equal(6, calc.multiply(2, 3));
    });
});
gulpfile.js
var gulp = require("gulp");
var mocha = require("gulp-mocha");

gulp.task("mocha", function() {
    return gulp
        .src(["test/*.js"], { read: false })
        .pipe(mocha({ reporter: "spec" }));
});

gulp.task("watch", function() {
    return gulp
        .watch(["src/**", "test/**"], ["mocha"]);
});
package.json
{
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-mocha": "3.0.1",
    "mocha": "^3.2.0"
  }
}

package.jsonscripts フィールドがないので、以下の実行はエラーになります。

Terminal
$ npm run mocha
npm ERR! missing script: mocha
$ npm run gulp mocha
npm ERR! missing script: gulp

でも yarn だと scripts フィールドがなくても問題なく実行されます。

2017/4/10 追記。run が無くても動くことに気づきました。

Terminal
$ yarn run mocha
// or
$ yarn mocha
yarn run v0.21.3
$ "/path/to/project/node_modules/.bin/mocha" 
  calc
    ✓ add
    ✓ multiply
  2 passing (12ms)
✨  Done in 0.66s.

$ yarn run gulp mocha
// or
$ yarn gulp mocha
yarn run v0.21.3
$ "/path/to/project/node_modules/.bin/gulp" mocha
[1X:33:00] Using gulpfile /path/to/project/gulpfile.js
[1X:33:00] Starting 'mocha'...
[1X:33:01] Finished 'mocha' after 686 ms
✨  Done in 8.62s.

npm run でエラーなく実行するには、以下のように scripts フィールドを追加する必要があります。

package.json
{
  〜略〜
  },
  "scripts": {
    "mocha": "mocha",
    "gulp": "gulp"
  }
}

そんなわけで自分はもっぱら yarn を使ってます。
install(yarn では add)も、npm より速い気がしますし。

でも Github とかで公開するコードでは scripts フィールドを書いておくと喜ばれるかも。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?