LoginSignup
2
3

More than 5 years have passed since last update.

TypeScriptで書いた.vueから.d.tsを生成する。

Posted at

やりたいこと

Vue.jsの単一ファイルコンポーネントを(vue-class-componentを使って)TypeScriptで書くときに、型定義ファイル(.d.ts)を生成して型の恩恵を受けたい。

やること

.vueファイルから、<script>タグの中身だけ抽出し、tscでコンパイルする。

ソースコード

PowerShellで書きました。
カレントディレクトリから.vueファイルを探して同じ場所に.d.tsを生成します。

# 定義ファイル生成対象の.vueファイルを取得
$vueFilePaths = Get-ChildItem . -Recurse -Include *.vue

# .vueファイルからscriptタグ内のみを抽出し、.tsファイルを生成
$tsFilePaths = @()
$vueFilePaths | ForEach-Object {
    $content = Get-Content $_.FullName
    # scriptタグの開始位置、終了位置
    $startLine = ($content | Select-String -Pattern '<script').LineNumber
    $endLine = ($content | Select-String -Pattern '</script>').LineNumber
    # .tsファイルを生成
    $vueFileDir = Split-Path $_.FullName
    $tsFileName = $_.Name -replace '\.vue', '.ts'
    $tsFilePath = "${vueFileDir}\${tsFileName}"
    $contentScript = $content[$startLine..($endLine - 2)]
    $contentScript | Out-File "${tsFilePath}" -Encoding utf8

    $tsFilePaths += $tsFilePath
}

# 型定義ファイルを生成
tsc --emitDeclarationOnly --declaration
# .tsファイルを削除
$tsFilePaths | Remove-Item

おわりに

vuetypeを使えば同じことができてとっても便利なのですが、
たまにうまく動かないときがあったので作ってみました。

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