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