LoginSignup
2
1

More than 5 years have passed since last update.

React16 最小構成のビルド環境 browserify babelify JSXあり

Last updated at Posted at 2018-04-01

関連記事

React16 最小構成のビルド環境 browserify reactify JSXあり - Qiita
https://qiita.com/standard-software/items/781ec3f491f4f1bea7b6

こちらの記事では Browserify で Reactify を使ったのですが、Babelも同時に使いたいという要望があると思われるので、React のための変換を Babelでやるようにするのがはやりのようですね。

ですので、Browserify の transform モジュールの babelify を使って変換を行います。

はじめに

環境は Windows 。 node.js インストール済みとします。

インストール

今回は browserify と reactify を使います。フォルダを決めてローカルインストールします。

  npm init -y
  npm install --save react
  npm install --save react-dom
  npm install --save browserify
  npm install --save-dev babel-cli
  npm install --save babel-preset-env
  npm install --save babel-preset-react
  npm install --save babelify

フォルダに、package.json が作られてその中身の一部はこのようになります。

  "dependencies": {
    "browserify": "^16.1.1",
    "react": "^16.3.0",
    "react-dom": "^16.3.0",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "babelify": "^8.0.0"
  },

ファイル

次の構成にします。決めたフォルダの中に次のファイルがある状態にしてください。

  index.html
  src フォルダ
    hello.jsx
  build フォルダ
    build.js

用意するのは、index.html と hello.jsx で、build.js は browserify によって生成されます。

index.html
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="app01"></div>
    <div id="app02"></div>
  <script src="./build/build.js"></script>
  </body>
</html>
hello.jsx
const React = require('react');
const ReactDOM = require('react-dom');

class HelloWorld extends React.Component {
  render() {
    return <div>Hello World {this.props.name}</div>;
  }
}

const hwElement = <HelloWorld name="01" />;
ReactDOM.render(hwElement,
  document.getElementById('app01'));

const hwFactory = React.createFactory(HelloWorld);
 ReactDOM.render(
  hwFactory({name: '02'}),
  document.getElementById('app02')
);

前の記事と同じです。

次にBabel用の設定ファイルを用意します

.babelrc
{
  "presets": ["env", "react"],
}

実行

ビルドコマンドは次のとおりです。決めたフォルダをカレントディレクトリにしてコマンド実行してください。

.\node_modules\.bin\browserify -t babelify .\src\hello.jsx -o .\build\build.js

実行結果は次のとおりになります。

<body>
    <div id="app01"><div data-reactroot="">Hello World 01</div></div>
    <div id="app02"><div data-reactroot="">Hello World 02</div></div>

これで、Babel を使って ESの最新と React の変換を行えます。

GitHub

2018/04/08追記

少しソースコードをシンプルにして次の場所に配置しました。
https://github.com/standard-software/React_Hello-World_Sample
CDN版 Reactのみ / React+JSX
Browserify版 Reactのみ / React+JSX Reactify / React+JSX Babelify
WebPack版 Reactのみ / React+JSX
これらが全て含まれています。

2
1
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
2
1