Reactプロジェクトの環境構築
react-scriptsを使わない方法を書く
react-create-app (react-scripts)は、内部でBabelとwebpackが動いている
init
$ git init
$ npm init -y
lisenceの修正
npmパッケージのインストール
code:sh
npm install react react-dom react-router-dom
npm install webpack webpack-cli webpack-dev-server copy-webpack-plugin --save-dev
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev
npm install css-loader style-loader --save-dev
内訳
react react-dom
react-router-dom
部分的にReactを導入する分には必要ない
babel/core @babel/preset-env @babel/preset-react babel-loader
css-loader style-loader
JavaScriptでCSSをimportする場合に必要
code:js
import "bootstrap/dist/css/bootstrap.min.css";
HTMLのscriptタグで指定するなら特に必要はない
CDNとか自前のCSSとか
とりあえず除いた(必要になったら上に移動)
@babel/cli
eslint babel-eslint eslint-loader eslint-plugin-react
$ mkdir src dist public
code:.gitignore
node_modules/
dist/
code:.babelrc
{
}
code:webpack.config.js
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const srcPath = path.join(__dirname, "src");
const publicPath = path.join(__dirname, "public");
const distPath = path.join(__dirname, "dist");
module.exports = {
entry: path.join(srcPath, "index.js"),
output: {
filename: "bundle.js",
path: distPath,
},
devServer: {
contentBase: publicPath,
port: 8081,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
],
},
plugins: [
new CopyPlugin({
patterns: from: publicPath, to: distPath },
}),
],
};
code:public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Sample</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
code:src/index.js
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.render(<h1>Hello, world!!</h1>, document.getElementById("root"));
code:package.json
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack --mode production"
},
確認
$ npm start
ブラウザが開いてHello Worldが表示される
参考