LoginSignup
3
4

More than 5 years have passed since last update.

Reactノート4(React,Babel,webpack,PostCSS )

Last updated at Posted at 2017-04-22

Reactトレーニング

React,Babel,webpack,PostCSS
参照: http://gihyo.jp/magazine/wdpress/archive/2017/vol97


スクリーンショット 2017-04-22 22.38.48.png

スクリーンショット 2017-04-22 22.44.29.png

package.json

package.json

{
  "name": "spa-note",
  "private": true,
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack"
  },
  "devDependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.26.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "postcss-easy-import": "^1.0.1",
    "postcss-loader": "^1.1.1",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-router": "^3.0.0"
  }
}
  • webpackのバージョンは1系

webpack.config.js

webpack.config.js

const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
//エントリーポイント
  entry: {
    js: './src/main.js',
    css: './src/main.css',
  },
  output: {
    path: './public',
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
//css-loaderとpoctcss-loaderを指定してCSSファイルをwebpackでビルドする
        loader: ExtractTextPlugin.extract('css-loader!postcss-loader'),
      },
    ],
  },
//変換対象のファイルを監視して変更があったら自動再変換、自動でリロードを行う。
  devServer: {
    contentBase: './public',
    inline: true,
    port: 8080,
    historyApiFallback: true,
    stats: {
      version: false,
      hash: false,
      chunkModules: false,
    },
  },
//extractTextPluginを使い、CSSファイルを外部ファイルとして出力するよう設定
  plugins: [
    new ExtractTextPlugin('bundle.css'),
  ],
//ワイルドカードを指定して@importができるプラグインを使う
  postcss: [
    require('postcss-easy-import')({ glob: true }),
  ],
  devtool: 'source-map',
};

.babelrc

{
  "presets": ["es2015", "react"]
}

index.html

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<link rel="stylesheet" href="/bundle.css">
</head>
<body>
<div id="app"></div>
<script src="/bundle.js"></script>
</body>
</html>

src/main.js

src/main.js

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
 <h1>demo</h1>,
 document.getElementById("app")
);

src/main.js

main.css

@import 'styles/base.css';

src/styles/main.js

base.css

h1 {
  padding:20px;
  font-size:30px;
  color:#F00;
}

ビルド実行

$ ./node_modules/.bin/webpack 

サーバー起動

$ ./node_modules/.bin/webpack-dev-server

3
4
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
4