Skip to content

Instantly share code, notes, and snippets.

@ukyo
Created February 16, 2018 10:46
Show Gist options
  • Save ukyo/37e43a88f717bb4e1ca6c12cb809a232 to your computer and use it in GitHub Desktop.
Save ukyo/37e43a88f717bb4e1ca6c12cb809a232 to your computer and use it in GitHub Desktop.
jsx or tsxからオレオレvirtual dom作る関数に渡す例

babel使ったときの例

package.json

{
  "name": "my-jsx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel src --out-dir dist",
    "watch": "babel --watch src --out-dir dist"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.0.0-beta.40",
    "@babel/core": "^7.0.0-beta.40",
    "@babel/plugin-syntax-object-rest-spread": "^7.0.0-beta.40",
    "@babel/plugin-transform-react-jsx": "^7.0.0-beta.40",
    "@babel/preset-env": "^7.0.0-beta.40",
    "@babel/preset-react": "^7.0.0-beta.40"
  }
}

.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    [
      "@babel/plugin-syntax-object-rest-spread",
      {
        "useBuiltIns": true
      }
    ],
    [
      "@babel/plugin-transform-react-jsx",
      {
        "pragma": "hoge",
        "pragmaFrag": "fuga",
        "throwIfNamespace": true,
        "useBuiltIns": true
      }
    ]
  ]
}

src/app.jsx

const f = () => (
  <><h1>aaaa</h1></>
);

dist/app.js

var f = function f() {
  return hoge(fuga, null, hoge("h1", null, "aaaa"));
};

TypeScript使ったときの例

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react",
    "jsxFactory": "hoge",
    "noImplicitAny": false
  }
}

foo.tsx

const hoge = () => {};

const Title: any = (text: string) => <h1 a b c>{text}</h1>;

const a = (text: string) => (
  <div>
    <div {...text} for={1}>{text}</div>
    <Title text={text} />
  </div>
);

foo.js

const hoge = () => { };
const Title = (text) => hoge("h1", { a: true, b: true, c: true }, text);
const a = (text) => (hoge("div", null,
    hoge("div", Object.assign({}, text, { for: 1 }), text),
    hoge(Title, { text: text })));

fragmentの省略記法はオレオレvdom関数では使えません。 TypeScriptだと型チェックされるのでこっちのほうが好き。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment