0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

webpackを使って既存のwebフレームワークにReactを動かしてみた

Last updated at Posted at 2022-07-03

Background

CDNのみでReactを動かそうとしたのですが、CDNが非対応のライブラリが多そうと思いました。それで、webpackを使ってひとつのjsファイルを出力してみようと思います。

Motivation

WordCloudを表示させたい!!
react-tagcloudのパッケージを使います。
スクリーンショット 2022-07-03 10.41.12.png

Demoページはここ
慣れてくれば他のvisualize用のライブラリを使ってみようと思ってます。

Method

  1. プロジェクトを作成
  2. 必要なパッケージをインストール
  3. webpackの設定
  4. package.json にwebpackの実行コマンドを追加
  5. 出力先フォルダを作成

Compose Environment

プロジェクトを作成
mkdir frontend
cd frontend
必要なパッケージをインストール
package.json を作成
touch package.json
package.json
{
  "name": "react-editor",
  "version": "1.0.0",
  "scripts": {
    "start": "echo 'Hello! package.json'"
  }
}

npm initpackage.json を作成できるみたいですが。 必要最低限の内容として name version scripts だけで良いみたいです。

この状態で package.json 直下で npm start とコマンドすると Hello! package.json が出力されると思います。

$ npm start

> react-editor@1.0.0 start
> echo 'Hello! package.json'

Hello! package.json
インストール

追加するのは webpack react babelの3つです。
あとはお好みでreactのライブラリをインストールします。

npm install webpack
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader
npm install react react-dom
npm install react-tagcloud
webpackの設定

webpackの設定には webpack.config.js が必要です。 touch で空のファイルを作成します。

touch webpack.config.js
webpack.config.js

const path = require('path')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dst'),
    filename: 'react_index.js',
  },
  resolve: {
    extensions: ['.js', '.ts', '.jsx']
  },
  module: {
    rules: [{
      test: /\.(js|mjs|jsx)$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-react',
            ]
          }
        }
      ]
    }]
  }
}

entry で最初に読み込むファイルを設定し、 outputで出力先のフォルダパスとファイル名を設定します。 resolve はここに拡張子を書いておくと実行読み込み時にimport文を簡略化することができます。例えば ./components/WordCloud.jsxをインポートしたい場合、 resolveextensions: ['.jsx']
設定しておくと import {SimpleCloud} from './components/WordCloud.jsx' と書かずに .jsxを省略して import {SimpleCloud} from './components/WordCloud' と書くことができます。 module.rules は 最新版のJavaScriptの記述に変換するためにBabelLoaderを設定しています。React の環境構築(セットアップ) を丸パクリして設定してます:sweat_smile:。 (webpackでbabel-loaderを使う方法を紹介を参照)

package.json にwebpackの実行コマンドを追加

package.jsonscriptsbuild のコマンドを追加します。

package.json
{
  ...
  "scripts": {
    "start": "echo 'Hello! package.json'",
    "build": "webpack --mode=production"
  }
  ...
}
出力先フォルダを作成

出力先のフォルダを作成します。

mkdir dst

これで npm run build すれば dst フォルダにjsファイルが出力できると思います。

Folder Structure

フォルダ構成は下記の通りとなります。

frontend(プロジェクトのディレクトリ)
├── dst  //出力先(output)フォルダ
│   └── react_index.js
└── src
    ├── components
    │       └── WordCloud.jsx
    ├── App.js
    └── index.js  //エントリポイント

Development

詳しいReactの開発については割愛します。 コードのみを掲載します。

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

let dom = document.querySelector("#root");
ReactDOM.render(<App />, dom);

App.js
import React from 'react'
import {SimpleCloud} from './components/WordCloud.jsx'

const App = () => {
  return (
    <>
      <div className="App">
        <h1>
          Hello, React!!!
        </h1>
      </div>
      <div>
        <SimpleCloud />
      </div>
    </>
  )
}

export default App;
components/WordCloud.jsx
import React from 'react'
import { TagCloud } from 'react-tagcloud'

const data = [
  { value: 'JavaScript', count: 38 },
  { value: 'React', count: 30 },
  { value: 'Nodejs', count: 28 },
  { value: 'Express.js', count: 25 },
  { value: 'HTML5', count: 33 },
  { value: 'MongoDB', count: 18 },
  { value: 'CSS3', count: 20 },
  { value: 'Django', count: 40 },
  { value: 'Python', count: 55 },
]

const SimpleCloud = () => (
  <TagCloud
    minSize={12}
    maxSize={35}
    tags={data}
    onClick={tag => alert(`'${tag.value}' was selected!`)}
  />
)

export {SimpleCloud};

Launcher

プロジェクト直下で下記のコマンドで実行します。成功すれば dstフォルダにjsファイルが出力されます。

$ npm run build

$ ls dst
react_index.js

Preview

あとは表示したいページにscriptタグを追加すれば完了です。
Djangoベースで書いています。出力したjsファイルはどこかに格納してください。
<div id="root"></div> はないと表示されません。

index.html
...
<div id="root"></div>
<script type="text/javascript" src="{% static 'js/react_frontend/react_index.js' %}"></script>
...

Consequence

スクリーンショット 2022-07-03 12.55.49.png

PostScript

忘れそうなので書いてみたった。
グラフ表示ライブラリは何を使えばいいか悩む。

Reference

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?