5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Elixir/Phoenixプロダクトへリプレイス②】フロント部分:JavaScriptをTypeScriptにリプレイスする例

Last updated at Posted at 2021-01-20

概要

こちらの 「Elixir/PhoenixでTypeScriptを使えるようにする。」を実装したPhoenixプロダクトのJavaScript部分をTypeScriptにリプレイスする手順を残しておく。

手順

リプレイス前のjsファイルをfilename.jsとする。

1. filename.jsをassets/js配下に配置

JSファイルをコピーしてペースト

2. ファイル名filename.jsをfilename.tsに変更

3. html部分を書き換える

filename.html.eex

-<a href="javascript:void(0);" onclick="CallScript();">JS呼び出す</a><
+<a href="javascript:void(0);" id="call_script">TS呼び出す</a>

4.filename.tsをTypeScriptに書き換える

filename.ts

+class Filename {
+    constructor() {
+        let call_script = document.getElementById("call_script");
+        call_script!.addEventListener("click", (e: Event) => this.CallScript());
+    }
+
-function CallScript() {
-  console.log("OK");
-};
+    CallScript() {
+        console.log("OK");
+    }
+}
+new SayonalaJa();

5.webpack.config.jsに記述

    entry: {
      'app': './js/app.js',
+     'filename': './js/filename.ts',
    },

6.layout部分でsrcを読み込む実装を追記

例えば、app.html.eexで読み込む。

    <script src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
+   <script src="<%= Routes.static_path(@conn, "/js/filename_ja.js") %>"></script>
  </body>
5
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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?