All Articles

npm-scripts で静的サイトの制作環境を構築 (2)

Pug * PostCSS * Babel * webpack * Browsersync

WindowsVisual Studio CodeYarnnpm-scriptsPugPostCSSBabelwebpack で静的サイトの制作環境を構築した際のメモ。(package.json ファイルの生成~ npm-run-all のインストール)

長くなったので、(1) コンパイラのインストール~ .gitignore ファイルの生成(2) package.json ファイルの生成~ npm-run-all のインストール(3) 構文ハイライトのインストール~ファイル保存時に自動整形、の 3 つに分けました。

Prettier の prettier.eslintIntegrationprettier.stylelintIntegration が非推奨になったため、(3) (改) 構文ハイライトのインストール~ファイル保存時に自動整形を投稿しました。

eslint-plugin-prettierstylelint-prettier が非推奨になり、stylelint v15 以降は stylelint-config-prettier が不要になったため、(3) (改) (2) 構文ハイライトのインストール~ファイル保存時に自動整形を投稿しました。

目次

package.json ファイルの生成

npm プロジェクトの情報が格納される package.json ファイルを生成します。

yarn init --yes

Pug のインストール

Pug をインストール

HTML のコーディングには Pug を使いたいので、pug – npm をインストールします。

yarn add pug --dev

pug-cli をインストール

pug-cli で _ がついたファイル(_header.pug)やディレクトリ(_include)もコンパイルされてしまう問題を解決する – Qiita を参考に、pug-cli – npm はインストールせずに、GitHub – pugjs/pug-cli: Pug’s CLI interface をインストールします。

yarn add github:pugjs/pug-cli#master --dev

Pug のコマンド・エイリアスを定義

package.json の scriptscompile-pug というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug"  }
}

コマンド・オプションは --out dist で出力フォルダを指定、--basedir src/pug で階層の基準フォルダを指定、--pretty で出力コードを整形、src/pug で入力フォルダを指定しました。

PostCSS のインストール

PostCSS をインストール

CSS のコーディングには Sass を使うのが一般的かと思いますが、Sass に拘りがある訳ではないので、お目当ての Autoprefixer に必要な PostCSS だけで済ませることにし、postcss – npm をインストールします。

yarn add postcss --dev

PostCSS CLI をインストール

postcss-cli – npm をインストールします。

yarn add postcss-cli --dev

postcss-import をインストール

別ファイルの読み込みに postcss-import – npm をインストールします。

yarn add postcss-import --dev

PostCSS Custom Properties をインストール

変数の定義に postcss-custom-properties – npm をインストールします。

yarn add postcss-custom-properties --dev

PostCSS Nesting をインストール

入れ子記法に postcss-nesting – npm をインストールします。

yarn add postcss-nesting --dev

Autoprefixer をインストール

ベンダープリフィックスの自動付与に autoprefixer – npm をインストールします。

yarn add autoprefixer --dev

postcss-csso をインストール

CSS の圧縮は css-minification-benchmark results を参考に CSSO に決め、postcss-csso – npm をインストールします。

yarn add postcss-csso --dev

PostCSS の設定ファイルを作成

プロジェクト・ルートに postcss.config.js ファイルを作成します。

module.exports = {
  map: {
    inline: false,
  },
  plugins: {
    "postcss-import": {},
    "postcss-custom-properties": {},
    "postcss-nesting": {},
    autoprefixer: {
      cascade: false,
      grid: true,
    },
    "postcss-csso": {},
  },
};

map: { inline: false } でソース・マップを埋め込みから外部ファイルへ変更、plugins: { } にプラグインを適用する順に記述、autoprefixer: { cascade: false, grid: true } で出力コードの整形を抑止、CSS Grid の IE 11 対応を設定しました。

対象ブラウザの設定ファイルを作成

プロジェクト・ルートに .browserslistrc ファイルを作成します。

# Browsers that we support

> 0.5% in JP
Firefox ESR

> 0.5% in JP で日本国内のシェアが 0.5% より多く、Firefox ESR で Firefox 延長サポート版を設定しました。

PostCSS のコマンド・エイリアスを定義

package.json の scriptscompile-pcss というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug",
    "compile-pcss": "postcss src/pcss/style.pcss --map --output dist/css/style.min.css"  }
}

コマンド・オプションは src/pcss/style.pcss で入力ファイルを指定、--map でソース・マップを作成、--output dist/css/style.min.css で出力ファイルを指定しました。

Babel のインストール

@babel/core をインストール

JavaScript のトランスパイルには Babel を使いたいので、@babel/core – npm をインストールします。

yarn add @babel/core --dev

@babel/preset-env をインストール

@babel/preset-env – npm をインストールします。

yarn add @babel/preset-env --dev

@babel/plugin-transform-runtime をインストール

@babel/plugin-transform-runtime – npm をインストールします。

yarn add @babel/plugin-transform-runtime --dev

Babel の設定ファイルを作成

プロジェクト・ルートに babel.config.js ファイルを作成します。

module.exports = (api) => {
  const presets = [
    [
      "@babel/preset-env",
      {
        useBuiltIns: false,
      },
    ],
  ];
  const plugins = [
    [
      "@babel/plugin-transform-runtime",
      {
        corejs: false,
        helpers: true,
        regenerator: true,
        useESModules: false,
      },
    ],
  ];

  api.cache(true);

  return {
    presets,
    plugins,
  };
};

対象ブラウザは PostCSS で設定した .browserslistrc ファイルを参照させるので targets: { } では指定せず、ポリフィルは @babel/plugin-transform-runtime に任せました。

webpack のインストール

webpack をインストール

JavaScript のビルドには webpack を使いたいので、webpack – npm をインストールします。

yarn add webpack --dev

webpack CLI をインストール

webpack-cli – npm をインストールします。

yarn add webpack-cli --dev

Babel Loader をインストール

babel-loader – npm をインストールします。

yarn add babel-loader --dev

webpack の設定ファイルを作成

プロジェクト・ルートに webpack.config.js ファイルを作成します。

const path = require("path");

module.exports = {
  mode: "production", // 'production' | 'development' | 'none'
  // Chosen mode tells webpack to use its built-in optimizations accordingly.
  entry: "./src/js/script", // string | object | array
  // defaults to './src'
  // Here the application starts executing
  // and webpack starts bundling
  output: {
    // options related to how webpack emits results
    path: path.resolve(__dirname, "dist/js"), // string
    // the target directory for all output files
    // must be an absolute path (use the Node.js path module)
    filename: "script.min.js", // string
    // the filename template for entry chunks
  },
  module: {
    // configuration regarding modules
    rules: [
      // rules for modules (configure loaders, parser options, etc.)
      {
        test: /\.js?$/,
        loader: "babel-loader",
        // the loader which should be applied, it'll be resolved relative to the context
        // -loader suffix is no longer optional in webpack2 for clarity reasons
        // see webpack 1 upgrade guide
        options: {
          presets: ["@babel/preset-env"],
        },
        // options for the loader
      },
    ],
  },
  devtool: "source-map", // enum
  // enhance debugging by adding meta info for the browser devtools
  // source-map most detailed at the expense of build speed.
};

mode: 'production' で出力ファイルを最適化、entry: './src/js/script' で入力ファイルを指定、output: { } で出力ファイルを指定、loader: 'babel-loader' で Babel を使用、devtool: 'source-map' でソース・マップ作成を設定しました。

webpack のコマンド・エイリアスを定義

package.json の scriptscompile-js というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug",
    "compile-pcss": "postcss src/pcss/style.pcss --map --output dist/css/style.min.css",
    "compile-js": "webpack"  }
}

コマンド・オプションは webpack.config.js ファイルで設定したのでありません。

ファイルの変更を監視するスクリプトの作成

Chokidar をインストール

pug-cli、postcss-cli、webpack-cli の何れにもファイルの変更を監視するコマンド・オプションがありますが、監視の開始時に対象ファイルの全てに対してコンパイルやビルドを行ってしまうのが嫌なので、chokidar – npm を使って自前で監視します。

yarn add chokidar --dev

Chokidar CLI をインストール

chokidar-cli – npm をインストールします。

yarn add chokidar-cli --dev

node-notifier をインストール

エラーの発生時にデスクトップ通知を表示したいので、node-notifier – npm をインストールします。

yarn add node-notifier --dev

スクリプト・ファイルを作成

プロジェクト・ルートに変更を検出したファイルのコンパイルやビルドを行う compile.js ファイルを作成します。

/* eslint-disable import/no-extraneous-dependencies, no-console */

// モジュールを読み込む
const cpexec = require("child_process").exec; // コマンド実行
const fsmkdir = require("fs").mkdir; // ディレクトリ作成
const notifier = require("node-notifier"); // デスクトップ通知
const path = require("path"); // パス文字列操作

// 拡張子ごとに入力元の基準ディレクトリを設定
const baseDir = {
  ".js": "src/js",
  ".pcss": "src/pcss",
  ".pug": "src/pug",
};

// 拡張子ごとに出力先の基準ディレクトリを設定
const outDir = {
  ".js": "dist/js",
  ".pcss": "dist/css",
  ".pug": "dist",
};

// 引数からパスを取得
const srcPath = path.normalize(process.argv[2]);

// パスから拡張子を取得
const extStr = path.extname(srcPath);

// 出力先のディレクトリ・パスを生成
const outPath = path.join(
  outDir[extStr],
  path.relative(baseDir[extStr], path.dirname(srcPath)),
);

// コンパイル・コマンドを生成
let cmdStr = "";

switch (extStr) {
  // 拡張子.js用コンパイル・コマンド
  case ".js":
    // Usage: webpack [options]
    cmdStr = "webpack";
    break;

  // 拡張子.pcss用コンパイル・コマンド
  case ".pcss":
    // Usage: postcss [input.css] [options] [-o|--output output.css]
    cmdStr =
      "postcss src/pcss/style.pcss --map --output dist/css/style.min.css";
    break;

  // 拡張子.pug用コンパイル・コマンド
  case ".pug":
    // Usage: pug [options] [dir|file ...]
    cmdStr = `pug --out ${outPath} --basedir ${baseDir[extStr]} --pretty ${srcPath}`;
    break;

  // 登録外拡張子用メッセージ
  default:
    cmdStr = `echo Command for "${extStr}" is not registered.`;
}

// 出力先のディレクトリを作成(Node.js v10.12 以降)
fsmkdir(outPath, { recursive: true }, (err) => {
  // エラー処理
  if (err) {
    throw err;
  } else {
    // コンパイル・コマンドを実行
    cpexec(cmdStr, (error, stdout) => {
      // エラー処理
      if (error) {
        // デスクトップ通知を表示
        notifier.notify({
          title: "An error has occured",
          message: "Check the terminal for more information",
        });
        // コンソールにエラー・ログを表示
        console.log(error);
      } else {
        // コンソールにログを表示
        console.log(stdout);
      }
    });
  }
});

複数ファイルの同時変更は想定していないので、エディタで すべて保存 はしないことにします。

変更監視のコマンド・エイリアスを定義

package.json の scriptswatch-compile というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug",
    "compile-pcss": "postcss src/pcss/style.pcss --map --output dist/css/style.min.css",
    "compile-js": "webpack",
    "watch-compile": "chokidar src/js/**/*.js src/pcss/**/*.pcss src/pug/**/*.pug --ignore src/**/_*.* --command \"node compile.js {path}\""  }
}

コマンド・オプションは src/js/**/*.js src/pcss/**/*.pcss src/pug/**/*.pug で監視するファイルを指定、--ignore src/**/_*.* で除外するファイルを指定、--command \"node compile.js {path}\" で実行するコマンドを指定しました。

Browsersync のインストール

Browsersync をインストール

静的サイトのブラウザでの確認には webpack-dev-server より Browsersync の方が向いていると思うので、browser-sync – npm をインストールします。

yarn add browser-sync --dev

Browsersync の設定ファイルを生成

プロジェクト・ルートに bs-config.js ファイルを生成します。

yarn run browser-sync init

生成した bs-config.js ファイルを編集します。

module.exports = {
  // files: false,
  files: ['dist/**/*.html', 'dist/css/**/*.css', 'dist/js/**/*.js'],  // server: false,
  server: {    baseDir: 'dist',    directory: true,  },};

files: ['dist/**/*.html', 'dist/css/**/*.css', 'dist/js/**/*.js'] で監視するファイルを指定、server: { baseDir: 'dist', directory: true } でルート・ディレクトリを指定、ディレクトリ・リスティングを有効にしました。

Browsersync のコマンド・エイリアスを定義

package.json の scriptswatch-server というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug",
    "compile-pcss": "postcss src/pcss/style.pcss --map --output dist/css/style.min.css",
    "compile-js": "webpack",
    "watch-compile": "chokidar src/js/**/*.js src/pcss/**/*.pcss src/pug/**/*.pug --ignore src/**/_*.* --command \"node compile.js {path}\"",
    "watch-server": "browser-sync start --config bs-config.js"  }
}

コマンド・オプションは start で Browsersync を開始、--config bs-config.js で設定ファイルを指定しました。

npm-run-all のインストール

npm-run-all をインストール

複数の npm-scripts を実行する npm-run-all – npm をインストールします。

yarn add npm-run-all --dev

npm-run-all のコマンド・エイリアスを定義

package.json の scriptsstart というコマンド・エイリアスを設定します。

{
  "scripts": {
    "compile-pug": "pug --out dist --basedir src/pug --pretty src/pug",
    "compile-pcss": "postcss src/pcss/style.pcss --map --output dist/css/style.min.css",
    "compile-js": "webpack",
    "watch-compile": "chokidar src/js/**/*.js src/pcss/**/*.pcss src/pug/**/*.pug --ignore src/**/_*.* --command \"node compile.js {path}\"",
    "watch-server": "browser-sync start --config bs-config.js",
    "start": "npm-run-all --parallel watch-*"  }
}

コマンド・オプションは --parallel watch-*watch-compilewatch-server の並列実行を指定しました。

Published Dec 29, 2018

ありふれた備忘録

いつか役立つかもしれないメモ

isonishi

小規模ウェブサイトの制作を請け負うフリーランサーです。