Nukindex 開発ブログ

アダルトサイトNukindexの開発ブログです

CSS Moduleを導入した

View に関してはこれで一段落。

作成したもの

CSS Moduleの導入

期待する動き

cssファイルを使ってコンポーネント毎にスタイルを定義する。ビルド時にひとつのcssファイルにまとめて出力する。

結果

成功

事例が探せなかったので苦労した。

手順など

コンポーネントディレクトリに style.css を作成する。

ROOT_DIRECTORY/
  + node_modules/
  + build/
  + source/
  |   + renderer/
  |   |   + components/
  |   |   |   + app/
  |   |   |   |   + view.js
  |   |   |   |   + style.css
  |   |   |   |
  |   |   |   + header/
  |   |   |       + view.js
  |   |   |       + style.css
  |   |   |
  |   |   + renderer.js
  |   |
  |   + index.html
  |
  + gulpfile.babel.js
  + .babelrc
  + package.json

gulpfile 内にCSSモジュールの使用準備をする。

$ npm install css-modulesify --save-dev

gulpfile.babel.js

browserify のプラグインとして導入する。

import gulp from "gulp";
import browserify from "browserify";
import babelify from "babelify";
import source from "vinyl-source-stream";
import transform from "vinyl-transform";
import cssModulesify from "css-modulesify";

gulp.task("build", () => {
  buildHTML();
  buildRenderer();
});

function buildHTML() {
  gulp.src("source/**/*.html")
      .pipe(gulp.dest("build"));
}

function buildRenderer() {
  browserify({
    "entries": ["source/renderer/renderer.js"],
    "extensions": ["", ".js", ".jsx", ".css"]
  }).plugin(cssModulesify, {
    "output": "./build/styles/bundle.css" // CSSファイルの出力先を指定
  }).transform(babelify).bundle()
      .pipe(source("bundle.js"))
      .pipe(gulp.dest("build/renderer"));
}

source/renderer/components/header/style.css

普通のCSSファイル。

.container {
  background-color: #fff;
}

.title {
  margin: 16px 0 12px;
  padding: 0 24px;
}

.description {
  margin: 12px 0 16px;
  padding: 0 24px;
}

source/renderer/components/header/view.js

stylesCSSファイルをインポートする。 styles にはCSSファイルに定義したクラス名がプロパティとして入る。 className にそのプロパティを入れ込む。

import React from "react";
import CSSModules from "react-css-modules";
import styles from "./style";

export default class Component extends React.Component {
  render() {
    return (
      <header className={styles.container}>
        <h1 className={styles.title}>
          <a href="/">Nukindex</a>
        </h1>

        <p className={styles.description}>
          毎日のおかずを提供するサイトです
        </p>
      </header>
    );
  }
}

source/index.html

ビルドしたCSSファイルを読み込む。

<!DOCTYPE html>
<html>
<head>
  <title>Nukindex</title>
  <link rel="stylesheet" href="./styles/bundle.css">
</head>
<body>
  <div id="app"></div>

  <script src="./renderer/bundle.js"></script>
</body>
</html>

React のスタイリングとしては CSS in JS がメジャーなのか、 CSS modules の使用例はあまり見つけられなかった。

先例がないと初心者にはつらい。

nukindex.com