この記事はReactの勉強メモです。
最初はcreate-react-app
を使用して開発環境を構築していたが、自分の周囲ではcreate-react-app
を使用して開発している人は皆無でした。
そのため、create-react-app
を使用せずに最小限の環境を構築する方法を調べたので、メモします。
1. npm init
を実行
% npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (foo-site)
version: (1.0.0)
description:
entry point: (webpack.config.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/7280ayubihs/Workspace/foo-site/package.json:
{
"name": "foo-site",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
2. Reactをインストール
% npm install react react-dom
added 5 packages, and audited 6 packages in 646ms
found 0 vulnerabilities
3. webpackをインストール
% npm install --save-dev webpack webpack-cli webpack-dev-server
added 317 packages, and audited 323 packages in 7s
43 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
4. babelをインストール
% npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react
added 167 packages, and audited 490 packages in 4s
52 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
5. webpack.config.js
を作成・編集
webpack.config.js
を新規作成し、次のように編集する。
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/App.jsx',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/react'
]
},
},
],
},
],
},
devServer: {
static: {
directory: path.join(__dirname, 'dist'),
},
port: 3000,
},
resolve: {
extensions: [
'.js', '.jsx'
],
},
target: 'web',
};
6. src/App.jsx
を作成・編集
src/App.jsx
を新規作成し、次のように編集する。
src/App.jsx
import React from "react";
import { createRoot } from "react-dom/client";
const App = () => {
return(
<div>Hello World!</div>
);
};
const root = createRoot(document.getElementById("root"))
root.render(<App/>);
7. dist/index.html
を作成・編集
dist/index.html
を新規作成し、次のように編集する。
dist/index.html
<html>
<head>
<title>React Sample</title>
</head>
<body>
<div id="root"></div>
<script defer src="bundle.js"></script>
</body>
</html>
8. package.json
を編集
"dev": "webpack serve --open",
を追加する。
package.json
{
...省略...
"scripts": {
"dev": "webpack serve --open",
"test": "echo \"Error: no test specified\" && exit 1"
},
...省略...
}
9. 動作確認
ターミナルでnpm run dev
を実行して、動けばOKです。