目次
- はじめに
- やることまとめ
- 1. VSCode 拡張機能の追加
- 2. 下記コマンド実行
- 3. nuxt.config.js → nuxt.config.ts にリネーム
- 4. nuxt.config.ts の内容を以下の通りに設定
- 5. tsconfig.json作成(内容は以下)
- 6. package.json の scripts を以下の通りに修正
- 7. .eslintrc.js を以下の通りに修正
- 8. VSCode のワークスペース設定を以下の通りに設定(.vscode/setting.json)
- 9. TypeScript の Optional Chaining と Nullish Coalescing に対応する(2020/03/04 追加)
- 手順解説
- 参考記事
はじめに
Nuxt + TypeScript の環境構築記事です。(Nuxt は v2.10.0 以上のバージョンを前提とします)
Windows, Visual Studio Code(VSCode) を使用します。
2019/09/20 執筆
2020/03/04 動作確認済み
Nuxt TypeScript はまだ不安定な、移り変わりの多い分野とのことなので、Nuxt TypeScript 公式 も参照して、比較しながら読んで頂けると幸いです。
※パッケージマネージャーは yarn で説明していきます。npm 等、適宜読み替えてください。(yarn がわからない方向け → yarn とは|npm と yarn のコマンド早見表)
やることまとめ
diff 表記がわからない方向け
以下、コード掲載箇所の【左端に +, - がついて、緑や赤色でハイライトされている箇所】は、『+ マークの付いている行を追加』、『- マークの付いている行を削除』という意味です。
1. VSCode 拡張機能の追加
- Vetur
- ESLint
- Prettier - Code Fommatter
2. 下記コマンド実行
yarn create nuxt-app # ESLint, Prettier を選択(その他のオプションは自由です)
yarn add -D @nuxt/typescript-build @nuxtjs/eslint-config-typescript
yarn add nuxt @nuxt/typescript-runtime
yarn remove @nuxtjs/eslint-config
3. nuxt.config.js
→ nuxt.config.ts
にリネーム
4. nuxt.config.ts
の内容を以下の通りに設定
- export default {
+ import { Configuration } from '@nuxt/types'
+ const config: Configuration = {
...(中略)
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
- '@nuxtjs/eslint-module'
+ '@nuxtjs/eslint-module',
+ '@nuxt/typescript-build'
],
...(中略)
build: {
- /*
- ** You can extend webpack config here
- */
- extend(config, ctx){} // extend オプションが必要であれば残してください
}
}
+ export default config
5. tsconfig.json
作成(内容は以下)
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"moduleResolution": "node",
"lib": ["esnext", "esnext.asynciterable", "dom"],
"esModuleInterop": true,
"experimentalDecorators": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noImplicitAny": false,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": ["./*"],
"@/*": ["./*"]
},
"typeRoots": ["/types"],
"types": ["@types/node", "@nuxt/types"] // Axios を使うのであれば、"@nuxtjs/axios" も追加
},
"exclude": ["node_modules"]
}
6. package.json
の scripts
を以下の通りに修正
...(略)
"scripts": {
- "dev": "nuxt",
- "build": "nuxt build",
- "start": "nuxt start",
- "generate": "nuxt generate",
- "lint": "eslint --ext .js,.vue --ignore-path .gitignore ."
+ "dev": "nuxt-ts",
+ "build": "nuxt-ts build",
+ "start": "nuxt-ts start",
+ "generate": "nuxt-ts generate",
+ "lint": "eslint --ext .ts,.js,.vue --ignore-path .gitignore ."
},
...(略)
7. .eslintrc.js
を以下の通りに修正
module.exports = {
root: true,
parser: 'vue-eslint-parser', // 追加
parserOptions: {
parser: '@typescript-eslint/parser' // 'babel-eslint' を消して、代わりに追加
},
env: {
browser: true,
node: true
},
// extends, rules はお好みですが、筆者はこんな感じに設定しました🙄
extends: [
'@nuxtjs/eslint-config-typescript',
'plugin:prettier/recommended',
'prettier/vue',
],
plugins: [],
rules: {
'lines-between-class-members': 'error', // extends のルールに含まれているが、VSCode の ESLint に反映されないので、個別に指定
'no-async-promise-executor': 'error', // 同上
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/no-v-html': 'off',
'vue/html-closing-bracket-spacing': 'off',
'vue/max-attributes-per-line': [
2,
{
singleline: 5,
multiline: {
max: 1,
allowFirstLine: false
}
}
]
}
}
8. VSCode のワークスペース設定を以下の通りに設定(.vscode/setting.json
)
{
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false
},
"[typescript]": {
"editor.formatOnSave": false
},
"[vue]": {
"editor.formatOnSave": false
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.enable": true,
"eslint.run": "onType",
"vetur.validation.style": true,
"vetur.validation.template": true,
"vetur.format.defaultFormatter.js": "prettier",
"vetur.format.defaultFormatter.css": "prettier",
"vetur.format.defaultFormatter.less": "prettier",
"vetur.format.defaultFormatter.postcss": "prettier",
"vetur.format.defaultFormatter.scss": "prettier",
"vetur.format.defaultFormatter.stylus": "none",
"vetur.format.defaultFormatter.ts": "prettier"
}
9. TypeScript の Optional Chaining と Nullish Coalescing に対応する(2020/03/04 追加)
以下のコマンドを実行。
yarn add -D @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining
手順解説
VSCode 拡張機能のインストール
以下の拡張機能(Extension)をインストールします。
- Vetur
→ Vue のシンタックスハイライトや入力補完ができるようになります - ESLint
→ eslint による警告・エラーの表示を行います - Prettier - Code formatter
→ 上記 ESLint と連携して、コードのフォーマットを行います
Create Nuxt App
まずは Create Nuxt App します(詳しくは学びたい方は → インストール - Nuxt.js)
yarn create nuxt-app env-nuxt-typescript
? Project name env-nuxt-typescript
? Project description My excellent Nuxt.js project
? Author name 自由
? Choose the package manager 自由(Yarn がおすすめ)
? Choose UI framework 自由
? Choose custom server framework 自由
? Choose Nuxt.js modules 自由
? Choose linting tools
(*) ESLint ← チェック付けます
(*) Prettier ← チェック付けます
( ) Lint staged files ← これは自由
? Choose test framework 自由
? Choose rendering mode 自由
? Choose development tools 自由
インストールオプションでは、 ESLint, Prettier を選択してください(後に VSCode + ESLint + Prettier の設定紹介があります;不要な方はスルーしてください)。
その他のオプションは自由です。
TypeScript の設定
パッケージインストール
yarn add -D @nuxt/typescript-build
yarn add nuxt @nuxt/typescript-runtime
コマンドの 2 行目に nuxt
も指定していますが、これは nuxt
のバージョンを最新版にするために行っています。
※ @nuxt/typescript-build
および @nuxt/typescript-runtime
は、Nuxt 2.9
以上でのみ使用できます。
nuxt.config.ts
nuxt.config.js
を nuxt.config.ts
に変更し、以下ように内容を修正します。
- export default {
+ import { Configuration } from '@nuxt/types'
+ const config: Configuration = {
...(中略)
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
- '@nuxtjs/eslint-module'
+ '@nuxtjs/eslint-module',
+ '@nuxt/typescript-build'
],
...(中略)
extend(config, ctx) {}
}
}
-
+ export default config
tsconfig.json
以下のとおり、tsconfig.json
を作成します。
(設定内容について詳しく知りたい方は → tsconfig 日本語訳)
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"lib": ["esnext", "esnext.asynciterable", "dom"],
"esModuleInterop": true,
"experimentalDecorators": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noImplicitAny": false,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": ["./*"],
"@/*": ["./*"]
},
"typeRoots": ["/types"],
"types": ["@types/node", "@nuxt/types"] // Axios を使うのであれば、"@nuxtjs/axios" も追加
},
"exclude": ["node_modules"]
}
package.json
package.json
の scripts
を、Nuxt TypeScript 用に修正します。
nuxt
→nuxt-ts
に変更"lint"
で指定する拡張子に、.ts
を追加
...(略)
"scripts": {
- "dev": "nuxt",
- "build": "nuxt build",
- "start": "nuxt start",
- "generate": "nuxt generate",
- "lint": "eslint --ext .js,.vue --ignore-path .gitignore ."
+ "dev": "nuxt-ts",
+ "build": "nuxt-ts build",
+ "start": "nuxt-ts start",
+ "generate": "nuxt-ts generate",
+ "lint": "eslint --ext .ts,.js,.vue --ignore-path .gitignore ."
},
...(略)
ESLint の設定
パッケージインストール
yarn add -D @nuxtjs/eslint-config-typescript
yarn remove @nuxtjs/eslint-config
※Nuxt TypeScript ドキュメントによると、@nuxtjs/eslint-config
は @nuxtjs/eslint-config-typescript
に含まれているため、不要だとのことです。
.eslintrc.js
.eslintrc.js
を以下の通りに修正します。
module.exports = {
root: true,
parser: 'vue-eslint-parser', // 追加
parserOptions: {
parser: '@typescript-eslint/parser' // 'babel-eslint' を消して、代わりに追加
},
env: {
browser: true,
node: true
},
// extends, rules はお好みですが、筆者はこんな感じに設定しました🙄
extends: [
'@nuxtjs/eslint-config-typescript',
'plugin:prettier/recommended',
'prettier/vue',
],
plugins: [],
rules: {
'lines-between-class-members': 'error', // extends のルールに含まれているが、VSCode の ESLint に反映されないので、個別に指定
'no-async-promise-executor': 'error', // 同上
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/no-v-html': 'off',
'vue/html-closing-bracket-spacing': 'off',
'vue/max-attributes-per-line': [
2,
{
singleline: 5,
multiline: {
max: 1,
allowFirstLine: false
}
}
]
}
}
nuxt.config.ts
nuxt.config.ts
の build
の中身を空にします。extend(config, ctx){}
という記述が、@typescript-eslint/no-unused-vars
でエラーとなるためです。
...(略)
build: {
- /*
- ** You can extend webpack config here
- */
- extend(config, ctx){}
}
...(略)
VSCode の設定
VSCode にて、保存時に Prettier によるフォーマットが走るように設定します。
.vscode
フォルダを作成し、その中に setting.json
を作成します。
{
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false
},
"[typescript]": {
"editor.formatOnSave": false
},
"[vue]": {
"editor.formatOnSave": false
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.enable": true,
"eslint.run": "onType",
"vetur.validation.style": true,
"vetur.validation.template": true,
"vetur.format.defaultFormatter.js": "prettier",
"vetur.format.defaultFormatter.css": "prettier",
"vetur.format.defaultFormatter.less": "prettier",
"vetur.format.defaultFormatter.postcss": "prettier",
"vetur.format.defaultFormatter.scss": "prettier",
"vetur.format.defaultFormatter.stylus": "none",
"vetur.format.defaultFormatter.ts": "prettier"
}
TypeScript の Optional Chaining と Nullish Coalescing に対応する(2020/03/04 追加)
Nuxt TypeScript 公式ガイドの『セットアップ』の項にも記載されていますが、TypeScript 3.7 から導入された Optional Chaining と Nullish Coalescing を利用するには、以下 2 点を行う必要があります。
まずは、以下のコマンドを実行し、babel plugin をインストールします。
yarn add -D @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining
続いて、tsconfig.json の "target" を "es2018" に設定します。
※当記事に従って設定されていた場合、既に設定済みと思われます。
// tsconfig.json
{
"compilerOptions": {
"target": "es2018",
// ... 以後省略
}
参考記事
Nuxt + TypeScript
- Nuxt TypeScript ドキュメント
- 3 分でつくる 2019 年版 Nuxt.js TypeScript 開発環境設定
Vue.js to TypeScript の書き方一覧 - TypeScript な Nuxt.js を VSCode で開発