11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[react][webpack]Reactのビルド環境を構築する

Last updated at Posted at 2018-06-25

Reactの開発環境を整備する備忘録

  • create-react-appを使わずに自前でビルド環境を構築する

完成形

% tree -I node_modules
.
├── build
│   ├── bundle.js
│   └── index.html
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   ├── components
│   │   └── Hello.js
│   └── index.js
└── webpack.config.js

moduleのinstall

  • 必要なmoduleをinstallする
mkdir react-sample
cd react-sample
npm init -y
npm i react react-dom
npm i -D @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli webpack-dev-server style-loader css-loader babel-loader copy-webpack-plugin

設定ファイルの作成

webpack.config.js
const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');

const DEV_PORT = process.env.PORT || 3000;

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: { presets: ['@babel/env'] },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, 'build/'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.join(__dirname, 'build/'),
    port: DEV_PORT,
    hot: true,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new CopyPlugin([{ from: './public', to: '.' }]),
  ],
};
.babelrc
{
  "presets": ["@babel/env", "@babel/preset-react"]
}

scriptsの追加

  • package.jsonのscriptsに追記
package.json
  "scripts": {
    "start": "webpack-dev-server -d --open",
    "build": "webpack -p"
  },

Reactコードの作成

src/index.js
import React from "react";
import ReactDOM from "react-dom";
import Hello from "./components/Hello";

function App() {
  return (
    <div>
      <Hello name="ozaki25" />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
src/components/Hello.js
import React from "react";

function Hello({ name }) {
 return <h1>Hello {name}!</h1>
}

export default Hello;

htmlの作成

public/index.html
<title>hello react</title>
<div id="root"></div>
<script src="bundle.js"></script>

アプリの起動

開発モード

npm start
  • 3000ポートで起動する
  • ホットリロードがきいているのでファイルを保存するだけで画面が更新される

本番モード

npm run build
  • public/bundle.jsにビルドされたファイルが生成される
  • public配下を公開すればアプリを配信できる
brew install serve
serve build
  • デフォルトだと5000ポートで動作確認できる
11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?