LoginSignup
1
1

More than 5 years have passed since last update.

Vue で tsx を使う

Last updated at Posted at 2018-11-20

やること

  • vue.jsとTypeScriptを使っているプロジェクトでtsxを書けるようにします。

やれなかったこと

  • 型をいい感じにする(tsxの意味がないのでなんとかしたい)

tsx?

Reactで使われているjsxのTypeScript版です。

手順

1. tsconfig.json に以下の記述を追加する

tsconfig.json
{
  "compilerOptions": {
    ...
    "jsx": "react",
    "jsxFactory": "h"
    ...
  }
}

2. Foo.tsx を書く

render の第一引数が React.createElement に該当するやつです。
tsconfig.json"jsxFactory": "h" と記載したのは、これが関係しています。

JSXのファクトリ関数を自作する方法と、Reactと全然違う挙動をさせるサンプル が詳しいです。

Foo.tsx
import Vue from "vue";
import { Component } from "vue-property-decorator";

@Component
export class Foo extends Vue {
  render(h) {
    return <h1>HELLO WORLD!!!</h1>;
  }
}

3. index.ts (エントリポイント)を書く

import Vue from "vue";
import { Foo } from "./Foo";

new Vue({
  el: "#app",
  components: {
    app: Foo,
  }
});

4. 色々設定する

webpack.ts
const config: Configuration = {
  ...
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
      },
    ],
  },
};

以上です。よろしくお願いします。

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