LoginSignup
2
0

More than 5 years have passed since last update.

requirejs で jsx を babel-standalone で処理しつつ読み込む

Last updated at Posted at 2018-01-09

Q. こんなのいつ使うの

A.
パフォーマンス無視できる
ビルド環境用意するのが面倒

実装例

index.html
<script src="//unpkg.com/requirejs/require.js" data-main="config.js"></script>
main.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import {Main} from 'jsx!main.class'

ReactDOM.render(
  <Main cont="hoge" />,
  document.querySelector('#out'))
main.class.jsx
import React from 'react'
export const Main = props =>
  <div>{props.cont}</div>
config.js
require.config({
  paths: {
    babel: "https://unpkg.com/@babel/standalone/babel.min",
    react: "https://unpkg.com/react/umd/react.production.min",
    "react-dom": "https://unpkg.com/react-dom/umd/react-dom.production.min"
  }
});
require(['jsx!main'])
jsx.js
(() => {

const callMethod = name => obj =>
  obj[name]()
const transform = babel => code =>
  babel.transform(code, {presets: ['react', 'es2015']}).code
const format = code => `define((require, exports, module) => {
  ${code}
  ;return exports;})`

define(['babel'], babel => ({
  load: (name, req, onload, config) => {
    const path = req.toUrl(name) + '.jsx'
    fetch(path)
      .then(callMethod('text'))
      .then(transform(babel))
      .then(format)
      .then(onload.fromText.bind(onload))
      .catch(onload.error.bind(onload))
  }
}))

})()

参考文献

RequireJS使い方メモ
GitHub - icecreamliker/requirejs-babel-plugin: A better RequireJS plugin for babel
RequireJS + babel-standalone + JSX

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