Webpack4 + Babel7 + webpack-dev-serverでReactの環境作る


備忘録として c⌒っ゚д゚)っφ メモメモ...

インストール

Webpack4からwebpack-cliのインストールも必要になったらしい

npm i -D webpack webpack-cli webpack-dev-server

Babel7からcoreとかpresetとか諸々インストールの仕方から変わってた
babel-loaderだけは今までどおり

npm i -D @babel/core @babel/preset-env @babel/preset-react @babel/polyfill @babel/register babel-loader

あと今回はHtmlWebpackPluginも使ってみる

npm i -D html-webpack-plugin html-loader

最後にReact

npm i -S react react-dom

設定

Webpack

@babel/registerを入れたらWebpackの設定もwebpack.config.babel.jsで書けるようになるらしい(知らなかった

webpack.config.babel.js
import webpack from 'webpack'
import path from 'path'
import HtmlWebpackPlugin from 'html-webpack-plugin'

export default {
  mode: 'development',
  context: path.resolve(__dirname, 'src'),
  entry: './js/index.js',
  output: {
    path: path.join(__dirname, '/www'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' },
      { test: /\.html?$/, loader: 'html-loader' },
    ],
  },
  resolve: {
    modules: [ 'node_modules', path.resolve(__dirname, 'src/js') ],
    extensions: ['.js'],
  },
  devServer: {
    inline: true,
    contentBase: path.resolve(__dirname, 'www'),
    watchContentBase: true,
    hot: true,
    open: true,
    port: 8888,
  },
  devtool: 'inline-source-map',
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html'
    })
  ]
}

説明は割愛
多分特別なことはしてない一般的な設定だと思う

Babel

インストールが@babel/〜になったからか、.babelrcの書き方も変わってた
useBuiltIns設定書くと勝手にpolyfillやってくれるらしい

.babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage",
      "targets": { "browsers": ["last 2 versions"] }
    }],
    "@babel/preset-react"
  ],
  "plugins": [],
}

動かしてみる

動かすためのコマンドを追加

package.json
  "scripts": {
    "start": "webpack-dev-server --hot",
    "build": "webpack --config webpack.config.babel.js"
  },

あとは適当にファイルを用意

src/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>
<body>
  <div id="main"></div>
  <script src="bundle.js"></script>
</body>
</html>
src/js/index.js
import React from 'react'
import ReactDOM from 'react-dom'

const App = () => <div>Hello</div>

ReactDOM.render(
  <App />,
  document.getElementById('main'),
)

npm startで動けばOK