LoginSignup
0
0

More than 3 years have passed since last update.

【'21.03.24-27 記録】npmのインストール>gulp.jsのインストールを完了

Last updated at Posted at 2021-03-24

かねてより気になっていた、gulp.jsをインストールした。

gulp.jsを導入するメリット

元々画像の圧縮が自動化できる、という知識はあった。
画像の圧縮の自動化ができる=今までtiny.pngを使ってわざわざ圧縮していた作業がなくなる
ということなので、良きだなと思っていたのだが、どうやらそれ以外にもメリットがあるらしい。

何千ものプラグインが用意されており、

・画像、CSS、JSの圧縮ができる(=サイトの表示速度がアップでき、SEO対策になる))
・ローカルホストの立ち上げ(テスト環境)
・sassの自動更新
・エラー表示
・sassをcssに自動コンパイル(*コンパイル=変換)
・ftpでのアップロードをコマンドでできる

などなど、それ以外にも様々なサイト制作が楽チンになる。

なるほど。

とりあえずnode.jsをインストールする

Node.jsとは?

サーバーサイドで動作するjavascript。
フロントからサーバーまで1つの言語で記述することができる。
チャットなど、リアルタイムで反応が必要なアプリの開発などに向いているらしい。

npmとは?

Node Package Manager。パッケージ管理お助けポジション。
Node.jsで書かれている様々なパッケージ達を管理している。

npm init
→カレントディレクトリにpackage.jsonファイルが生成される。
 このファイル内に、npmでインストールしたファイル達が記述されていく。

npm install [インストールしたいパッケージ名]
→目的のパッケージ + 依存関係にあるパッケージを一緒にインストールしてくれる。便利。
 アンインストールなどもコマンドで簡単に行えるので管理がすごく楽そう。

(webpackとは?)

Node.jsで作られたパッケージの1つ。
npm install webpackでインストールできる。
役割はバンドラー(sourceまとめポジション)。
css、js、画像などを、様々な加工をしながらまとめてくれる。
設定はwebpack.config.jsに記述していく。
設定次第で色々便利に使えるらしい。下記はよく使われる例。

js:書式の変換、バンドル
scss:コンパイル、minify、autoplefixなど
画像とか:自動圧縮

公式サイトで、推奨版をDL.

ターミナルでバージョンが確認できたらDL完了。

terminal.terminal
%  node -v
v14.16.0

ここからはただの叩いたコマンドを記録してるだけ。

409 cd Documents/blogtest\n
410 cd Documents
411 mkdir blogtest
412 npm init
413 cd Documents
414 ls
415 cd blogtest
416 npm init\n
417 npm install gulp -g\n
418 sudo npm install gulp -g\n
419 npm install gulp --save-dev\n
420 cat pacage.json
421 var gulp = require("gulp");\n
422 ls
423 cat package.json

pacage.jsonの中身確認はcatでできるので必要なら見て。

npmって今までよく見てきた単語だけれど、
正直なんなんだかよくわかってなかったので、調べてみた。
【初心者向け】NPMとpackage.jsonを概念的に理解する

全部読んだけど、なるほどよくわからんという感じだった。
私今npmのパッケージを公開したの...??
MITライセンスにしたな〜なんでだろうな〜て思ったけどそういう事なんだろうか。

とりあえずそこまで危険性はない気がするので後回しにしたいと思う。

後から知ったけど、Node.jsをDLせず管理マネージャーを使う方がいいらしい。

先に言ってくれ。新しいMac汚れたやんね。

gulp@4.0.0 とgulp-sass をインストールする

gulp-sassをインストールする=プラグインをインストールするということみたい。

terminal.terminal
npm init -y
npm install -D gulp@4.0.0 gulp-sass

実行

//gulp-cliがインストールされている場合
gulp

//gulp-cliがインストールされていない場合
npx gulp

ここでエラー発生。

どちらも叩いたが、

% gulp
[10:16:18] No gulpfile found
% npx gulp
[10:16:27] No gulpfile found

gulpを入れ直してみる

とりあえずエラー文をぐぐると、このQiita記事が同じような現象だったので、
同様に

% sudo npm install -g gulp
を叩く。(本当はsudoやりたくないけど)

terminal.terminal
Password:
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
/usr/local/bin/gulp -> /usr/local/lib/node_modules/gulp/bin/gulp.js
+ gulp@4.0.2

4.0.2がインストールできたっぽい。
だが解決しなかった。

terminal.terminal
 % gulp
[10:23:47] No gulpfile found

えなんで?
とりあえずこの記事に-vでバージョンが確認できるとあったので、確認する。

% gulp -v
CLI version: 2.3.0
Local version: 4.0.0
//やっぱりgulpはインストールできてる

//アップデートをしてみる
% npm upgrade -g gulp
%gulp -v
CLI version: 2.3.0
Local version: 4.0.0
//変わらない。

% gulp
[10:28:41] No gulpfile found
% npx gulp
[10:30:17] No gulpfile found

なんでだーー

結論: gulpインストール後、gulpfile.jsを手動で作らないとだめらしかった

このStackOverflowの記事で、
「gulpを使いたいディレクトリで、gulpfile.jsを追加しないとだめなんやで。もし、gulpfile.jsがある状態でエラーが出るならgulpをnpm install -g gulpでアップデートしてみ」
と書いてあった。

あ、そっかgulpじゃなくてgulpfile.jsがないってエラーで言われてたわ。
上記で見つけたサイトでは、多分gulpfile.jsがある状態で、古いバージョンだったからエラーが出てたけど、私の場合はそもそもgulpfile.jsを作ってなかった。

terminal.terminal
//vimでgulpfile.jsを開く
% vi gulpfile.js

//以下テスト用のタスク追記
var gulp = require('gulp');
gulp.task('default', function () { console.log('Hello Gulp!') });
//:wp > Enterで保存&vimから出る

//gulpを実行するコマンドを実行
 % gulp
[10:59:19] Using gulpfile ~/Desktop/saastestfile/gulpfile.js
[10:59:19] Starting 'default'...
Hello Gulp!
[10:59:19] The following tasks did not complete: default
[10:59:19] Did you forget to signal async completion

できた!

gulpfile.jsにデフォルトタスクを登録していく

この方のブログ:【2021年最新】Gulp4 + Webpackの超オススメ設定を公開【爆速コーディング環境構築のgulp.jsの設定をコピペしました。

gulp4になってから、gulpfile.jsの書き方がgulp3の時とは変わったらしく、古い記事には注意らしいです。

gulpfile.js
const { src, dest, watch, series, parallel } = require("gulp");
// 直列処理(順番に処理):series(), 並列処理(順番を問わない):parallel()
const sass = require('gulp-sass');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssdeclsort = require('css-declaration-sorter');
const sassGlob = require('gulp-sass-glob'); // @importを纏めて指定
const browserSync = require('browser-sync');
const gcmq = require('gulp-group-css-media-queries'); // media queryを纏める
const mode = require('gulp-mode')({
  modes: ['production', 'development'], // 本番実装時は 'gulp --production'
  default: 'development',
  verbose: false,
})
const webpack = require("webpack");
const webpackStream = require("webpack-stream"); // gulpでwebpackを使うために必要なプラグイン

// webpackの設定ファイルの読み込み
const webpackConfig = require("./webpack.config");

const compileSass = done => {
  const postcssPlugins = [
    autoprefixer({
    // browserlistはpackage.jsonに記載[推奨]
    cascade: false,
    // grid: 'autoplace' // IE11のgrid対応('-ms-')
    }),
    cssdeclsort({ order: 'alphabetical' /* smacss, concentric-css */ })
  ]

  src("./src/scss/**/*.scss", { sourcemaps: true  /* init */})
  .pipe(plumber())
  .pipe(sassGlob())
  .pipe(sass({outputStyle: 'expanded'}))
  .pipe(postcss(postcssPlugins))
  .pipe(mode.production(gcmq()))
  .pipe(dest("./dist/css", { sourcemaps: './sourcemaps' /* write */ }));
  done(); // 終了宣言
}

// ローカルサーバ起動
const buildServer = done => {
  browserSync.init({
    port: 8080,
    notify: false,
  // 静的サイト
    server: {
      baseDir: './',
    },
    // 動的サイト
    // files: ['./**/*.php'],
    // proxy: 'http://localsite.wp/',
  })
  done()
}

// ブラウザ自動リロード
const browserReload = done => {
  browserSync.reload()
  done()
}

// webpack
const bundleJs = () => {
  // webpackStreamの第2引数にwebpackを渡す
  return webpackStream(webpackConfig, webpack)
    .pipe(dest("./dist/js"));
};

// ファイル監視
const watchFiles = () => {
  watch('./**/*.html', browserReload)
  watch('.src/scss/**/*.scss', series(compileSass, browserReload))
  watch('.src/js/**/*.js', series(bundleJs, browserReload))
}

exports.sass = compileSass;
exports.default = parallel(buildServer, watchFiles);

sassのプラグイン以外にも必要なプラグインを一括でインストールする

下記を全部コピペしてターミナルで実行

terminal.terminal
npm install gulp-sass gulp-plumber gulp-notify gulp-sass-glob browser-sync gulp-postcss autoprefixer css-declaration-sorter gulp-imagemin imagemin-optipng imagemin-mozjpeg gulp-ejs gulp-rename --save-dev

pacage.jsonを確認してインストールできてるか確認

terminal.terminal
%cat pacage.json

{
  "name": "saastestfile",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^10.2.5",
    "browser-sync": "^2.26.14",
    "css-declaration-sorter": "^6.0.2",
    "gulp": "^4.0.0",
    "gulp-ejs": "^5.1.0",
    "gulp-imagemin": "^7.1.0",
    "gulp-notify": "^3.2.0",
    "gulp-plumber": "^1.2.1",
    "gulp-postcss": "^9.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-sass": "^4.1.0",
    "gulp-sass-glob": "^1.1.0",
    "imagemin-mozjpeg": "^9.0.0"
  }
}

よく出てくるWatchってなんなの?

watch = タスクをまとめてgulpコマンドのみで実行できる便利機能。
で合ってるかな?

sassをコンパイルしたかったらgulp-sass
ejsをhtmlにまとめたかったら、gulp-ejs
などそれぞれのコマンドを打つ必要があります。
これでは、何か更新を加える度にそれぞれのコマンドを打つ必要があり面倒なのをまとめてくれる

らしいです。なるほどー。

node_modulesというファイルはgitnoreでgitにあげないよう設定しておくといいらしい。

参考にしたサイト

↑いろいろ拝見しましたが、導入手順については多分このサイトが一番わかりやすいと思います。動画つきです。

↑上記記事もかなりわかりやすいです。

↑上記サイトはgulpというよりはwebpack+gulpでの開発方法が解説されてますが、私がハマったエラー'gulpfile.js'について、デフォルトタスクを登録しないといけないことについて解説されています。

↑安心のLIGさんの記事ですが、若干古いです。プラグインについてだったりが解説されています。

0
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
0
0