技術ブログ

プログラミング、IT関連の記事中心

React(TypeScript)プロジェクトの作成方法(Docker、ESLint、Prettier、WebPack)【4/4】

目次


スポンサードリンク



事前準備

以下の記事の内容が完了している前提で本記事を記載しています。
まだの方は、以下から進めてください。

React(TypeScript)プロジェクトの作成方法(Docker、ESLint、Prettier、WebPack)【3/4】 - Reigle 技術ブログ

WebPack

必要なWebPackのライブラリをインストールする

npm install --save-dev webpack webpack-cli webpack-dev-server

必要なloader系のライブラリをインストールする

npm install --save-dev babel-loader @babel/preset-react ts-loader style-loader css-loader react-svg-loader

プロジェクトのルートに「webpack.config.js」を作成し、内容に以下を記載する。
※内容はサンプルなので、必要な設定を定義すること。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { LoaderOptionsPlugin } = require('webpack');

module.exports = () => {
  return {
    mode: 'development',
    context: __dirname,
    devtool: 'inline-source-map', //sourceMapを出力する
    entry: [
      path.join(__dirname, 'src/index.tsx'),
    ],
    output: {
      path: path.resolve(__dirname, 'build'),
      filename: 'bundle.js',
      publicPath: '/',
    },
    cache: true,
    plugins: [
      new LoaderOptionsPlugin({
        debug: true
      }),
      new HtmlWebpackPlugin({ //reactのテンプレートを読み込む
        template: './public/index.html',
        filename: 'index.html',
        favicon: './public/favicon.ico',
        manifest: './public/manifest.json',
      }),
    ],
    resolve: {
      alias: {
        "react-draftjs-editor": path.join(__dirname, '..', 'src/index.tsx'),
      },
      extensions: ['.json', '.js', '.jsx', '.ts', '.tsx'],
    },
    devServer: { // SPA対策
      historyApiFallback: true,
    },
    module: {
      rules: [{
        test: /\.(js|ts|tsx)$/,
        use: {
          loader: 'babel-loader',
        },
        exclude: /node_modules/,
        include: [
          __dirname,
          path.join(__dirname, '..', 'src'),
        ],
      }, {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        use: {
          loader: 'ts-loader',
        }
      }, {
        test: /\.css$/, // cssのファイル読み込みモジュールを指定
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.svg$/,
        use: [{
          loader: "babel-loader"
        }, {
          loader: "react-svg-loader",
          options: {
            jsx: true // true outputs JSX tags
          }
        }]
      }
    ]}
  }
};

プロジェクトのルートの「package.json」の「scripts」を以下の様に修正する。

"scripts": {
  "start": "webpack-dev-server --config webpack.config.js --port 3000 --progress --profile --static src/",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},

プロジェクトのルートの「tsconfig.json」を以下の様に修正する。
※内容はサンプルなので、必要な設定を定義すること。

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "sourceMap": true,
    "removeComments": true,
    "experimentalDecorators": true,
    "baseUrl": "./src",
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

プロジェクトの「public/index.html」を以下の様に修正する。
※不要な定義の削除

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

プロジェクトの「src/App.tsx」を以下の様に修正する。

import React from 'react';
import logo from './logo.svg';
// import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        {/* <img src={logo} className="App-logo" alt="logo" /> */}
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

プロジェクトの「.eslintrc.js」の「ignorePatterns」を以下の様に修正する。

"ignorePatterns": [
  "**/public/*",
  "**/node_modules/*",
  "**/.vscode/*",
  ".eslintrc.js",
  ".prettierrc.js",
  "webpack.config.js",
],

プロジェクトの「.prettierignore」に以下を追加する。

webpack.config.js

以下でプロジェクトを実行し、エラーが発生しなければ完成です。

docker-compose up


スポンサードリンク



完成

以上でプロジェクトのテンプレートは完成です。 完成版のソースコードは以下なので、クローンして各自でご利用ください。 ※それぞれ、お好きなようにカスタマイズしてください。

github.com