使用TypeScript和TSLint简化快速的类型检查和操作。
yarn add nuxt-typescript typescript tslint --dev
添加
nuxt-typescript到Nuxt的配置中:
// nuxt.config.js
module.exports = {
modules: ["nuxt-typescript"]
}
配置
tsconfig.json具有以下设置:
{
"compilerOptions": {
"jsx": "preserve",
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"~/*": ["./*"],
"@/*": ["./*"]
},
"strict": true,
"sourceMap": true,
"noUnusedLocals": true,
"experimentalDecorators": true
}
}
现在,您可以在Nuxt项目中使用TypeScript了:
// core/utils.ts
export function reverseString(value: string) {
return value
.split("")
.reverse()
.join("")
}
// store/index.ts
export const state = () => ({
title: "Nuxt + TypeScript"
})
<template>
<div>
<h1 v-text="title"/>
<input v-model="input"/>
<pre v-text="reversed"/>
</div>
</template>
<script lang="ts">
import { State } from 'vuex-class'
import { Component, Vue } from 'nuxt-property-decorator'
import { reverseString } from '~/core/utils'
@Component
export default class extends Vue {
@State public title: string
public input = 'TypeScript'
head() {
return {
title: this.title
}
}
get reversed(): string {
return reverseString(this.input)
}
}
</script>
查看工作示例。
如果要使用TSLint整理TypeScript文件,只需
tslint.json在项目的根目录下创建一个文件:
{
"defaultSeverity": "warning",
"extends": ["tslint:latest"]
}
建议您设置
defaultSeverity为“警告”,以便可以将棉绒错误与类型错误区分开。
可以通过Nuxt配置文件中
nuxt-typescript的
typescript对象将选项传递给:
// nuxt.config.js
module.exports = {
modules: ["nuxt-typescript"],
typescript: {
formatter: "default"
}
}
选项 | 类型 | 默认 | 描述 |
---|---|---|---|
tsconfig |
String |
“ tsconfig.json” | TypeScript配置文件的路径。 |
tslint |
String |
“ tslint.json” | TSLint配置文件的路径。 |
formatter |
String |
“代码帧” | 使用TSLint格式化程序。“默认”或“代码帧”。 |
parallel |
Boolean |
true |
thread-loader为生产版本启用/禁用。 |
checker |
Boolean |
true |
启用/禁用TypeScript检查器Webpack插件。 |
babel |
Object |
null |
Babel配置选项将与Nuxt的默认设置合并。 |
感谢Evan You和Kevin Petit在Vue CLI TypeScript插件上所做的工作,该插件是许多实现的基础。
感谢John Lindquist创建了Nuxt TypeScript示例,该示例启动了该项目。