Madogiwa Blog

主に技術系の学習メモに使っていきます。

Nuxt.jsに後からTypeSctiptを導入するときのMEMO📝

最近Nuxt.jsで作ったプロジェクトを作成後に後からTypeScriptを導入したときに色々とハマりどころがあったのでメモしておく。

前提

今回のNuxt.jsとTypeScriptのバージョン情報は下記のとおりです。

  • nuxt: 2.10.2
  • typescript: 3.7.4

また私が最初にNuxt.jsのプロジェクトを作成した際の設定は下記です。

create-nuxt-app v2.12.0
✨  Generating Nuxt.js project in .
? Project name foodolist-front
? Project description My delightful Nuxt.js project
? Author name Madogiwa
? Choose the package manager Npm
? Choose UI framework None
? Choose custom server framework None (Recommended)
? Choose Nuxt.js modules Axios
? Choose linting tools ESLint
? Choose test framework None
? Choose rendering mode Single Page App
? Choose development tools (Press <space> to select, <a> to toggle all, <i> to invert selection)

基本的な手順

まずNuxt.jsにTypeScriptを導入する方法は公式のドキュメントがあるのですが、それに従って導入するのはセオリーだと思います。

https://typescript.nuxtjs.org/ja/

しかし私の場合だとうまく行かなったので追加で行った手順を記載しておきます😢

Module parse failed: Unexpected character '@'が発生する・・・

下記に従ってpackage.jsonnuxtではなくnuxt-tsで起動するように修正しました。

qiita.com

// before
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore ."

//after
"scripts": {
    "dev": "nuxt-ts",
    "build": "nuxt-ts build",
    "generate": "nuxt-ts generate",
    "start": "nuxt-ts start",
    "lint": "eslint --ext .ts,.js,.vue --ignore-path .gitignore ."

公式のTypeScriptの導入ドキュメントではオプションとなっていたのですが実施しないと、 Module parse failed: Unexpected character '@'といったエラーが発生してうまく動きませんでした。。。

typescript.nuxtjs.org

Nuxt.jsのコミュニティでもRuntimeを使用しているので使用した方が良かったようです・・・!

typescript-template/package.json at master · nuxt-community/typescript-template · GitHub

eslint実行時にEnvironment key "jest/globals" is unknown + その他諸々が発生する・・・

eslint実行時にEnvironment key "jest/globals" is unknownや依存モジュールが認識されずコンソールに表示されるがまま色々なeslintまわりのプラグインを導入しました😇

  "devDependencies": {
    "eslint-plugin-jest": "^23.6.0",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-nuxt": ">=0.4.2",
    "eslint-plugin-unicorn": "^15.0.1",
    "eslint-plugin-vue": "^6.1.2"

この辺はtypescript-templateも記載されておらず正解がわからないのですが、一旦コンソールに表示されるがままにpackageをinstallしていくと動きました。。。 eslint-plugin-vueに関してはnode_modulesに依存により入っていたのですが、明示的にpackage.jsonに記載しないと認識してくれませんでした😢

typescript-template/package.json at master · nuxt-community/typescript-template · GitHub

おわりに

いろいろなネット上のの情報のおかげでなんとかNuxt.js + TypeScriptの環境を作れました😭
昨今のjs界隈ではTypeScriptがデファクトスタンダードになりつつあるようですが、あまりキャッチアップできていないので色々と試して理解を深めていきたい・・・!

参考

typescript.nuxtjs.org

github.com

qiita.com

qiita.com