LoginSignup
5
9

More than 5 years have passed since last update.

create-react-appでPostCSS環境を作る

Posted at

create-react-appを使って作成したReactアプリに、PostCSSの設定をしていきます。

【前提】
・node.jsがインストールされている
・create-react-appがグローバル環境にインストールされている

create-react-appでReactプロジェクトを作成します。

$ create-react-app myapp
$ cd ./myapp

postcss-cliとPostCSSのプラグインを追加していきます。

$ yarn add -D autoprefixer cssnano postcss-nested postcss-cli npm-run-all 

続いて、プロジェクトのルートディレクトリにpostcss.config.jsを作成します。

$ touch postcss.config.js
postcss.config.js
module.exports = {
  plugins: [
    require('postcss-nested'),
    require('autoprefixer'),
    require('cssnano')({
      preset: 'default',
    }),
  ],
};

App.cssstyles/main.cssにリネームします。

$ mkdir src/styles
$ mv src/App.css src/styles/main.css

App.jsからimport './App.css';を削除します。

main.cssでSassのようにネスト記法が使えるようになります。
このときに、テキストエディタのプラグイン等設定で、PostCSSに対応させておくと便利です。

src/styles/main.css
body, html {
  margin: 0;
  padding: 0;
}

.App {
  text-align: center;

    &-logo {
        animation: App-logo-spin infinite 20s linear;
        height: 80px;
    }

    &-header {
        background-color: #222;
        height: 150px;
        padding: 20px;
        color: white;
    }

    &-title {
        font-size: 1.5em;
    }

    &-intro {
        font-size: large; 
    }
}
@keyframes App-logo-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

package.json"scripts"を書き換えることで、
postcss-cliのコマンドを使って、
src/styles/main.cssをコンパイルしてsrc/index.cssにビルドしたいと思います。

package.json
{
// 一部抜粋
  "scripts": {
    "build:css": "postcss src/styles/main.css -o src/index.css",
    "watch:css": "postcss src/styles/main.css -o src/index.css -w",
    "start": "npm-run-all -p watch:css start-js",
    "start-js": "react-scripts start",
    "build-js": "react-scripts build",
    "build": "npm-run-all build:css build-js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
}

ビルド環境はこれで完成です。

開発環境
$ yarn start

ビルド
$ yarn build
5
9
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
5
9