インストール
npm init -y npm i -D webpack webpack-cli typescript ts-loader npm i -S react react-dom npm i -D @types/react @types/react-dom
package.jsonのscriptsにbuildとstartを追加
package.json
"scripts": { + "build": "webpack --mode=production", + "start": "webpack -w --mode=development" },
tsconfig.json生成
$ touch tsconfig.json
tsconfig.jsonを編集
{ "compilerOptions": { "sourceMap": true, "target": "es5", "module": "es2015", "strict": true, "strictNullChecks": true, "noUnusedLocals": true, "noUnusedParameters": false, "noImplicitReturns": true, "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "jsx": "react", "lib": ["es2020", "dom"] } }
webpack.config.json生成
$ touch webpack.config.js
webpack.config.jsonを編集
const path = require('path') const assetsDir = path.resolve(__dirname, 'public_html/assets'); module.exports = { entry: assetsDir + "/src/app.tsx", output: { path: assetsDir + "/dist", filename: 'app.js' }, module: { rules: [ { test: /\.tsx?$/, use: "ts-loader", }, ], }, resolve: { extensions: [".ts", ".tsx", ".js"] }, };
ビルドのテスト
$ mkdir -p public_html/assets/src
$ touch public_html/assets/src/app.tsx
app.tsx
import React from 'react' import { render } from 'react-dom' const App = () => { return ( <div> <div>Hello React</div> </div> ) } render(<App/>, document.querySelector('#app'))
ビルド
$ npm run build (または $ npm run start)
public_html/assets/distディレクトリにapp.jsが生成されている
app.jsの読み込み
public_html/index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>部分React</title> </head> <body> <div id="app"></div> <script src="assets/dist/app.js" charset="utf-8"></script> </body> </html>
.gitignoreの設定
https://raw.githubusercontent.com/facebook/react/main/.gitignore
.gitignore
.DS_STORE node_modules scripts/flow/*/.flowconfig .flowconfig *~ *.pyc .grunt _SpecRunner.html __benchmarks__ build/ remote-repo/ coverage/ .module-cache fixtures/dom/public/react-dom.js fixtures/dom/public/react.js test/the-files-to-test.generated.js *.log* chrome-user-data *.sublime-project *.sublime-workspace .idea *.iml .vscode *.swp *.swo packages/react-devtools-core/dist packages/react-devtools-extensions/chrome/build packages/react-devtools-extensions/chrome/*.crx packages/react-devtools-extensions/chrome/*.pem packages/react-devtools-extensions/firefox/build packages/react-devtools-extensions/firefox/*.xpi packages/react-devtools-extensions/firefox/*.pem packages/react-devtools-extensions/shared/build packages/react-devtools-extensions/.tempUserDataDir packages/react-devtools-inline/dist packages/react-devtools-shell/dist packages/react-devtools-timeline/dist
気をつけること
- app.jsをロードするときはDOMの末尾でロードする(先頭に追加するとJavaScriptコードが走らない)
- render()内の<div class="hoge">は<div className="hoge">に書き換える
- styleはJavaScriptオブジェクトに変更する。たとえば<div style="visibility: hidden;">は<div style={{visibility: 'hidden'}}<とする。