这是本文档旧的修订版!


创建Typescript项目

1、创建文件夹

直接创建typescipt文件夹 通过终端创建typescript文件夹

download

mkdir typescript
cd typescript

2、进入typescript文件夹,初始化npm

download

npm init

根据提示回车,这时候文件夹中会生成package.json文件。

3、安装typescript/tslint和NodeJS的类型声明

download

npm install --save-dev typescript tslint @types/node

tslint是代码规则检查工具,保持代码风格一致。这时候文件夹中就会生成node_modules文件夹

4、配置tsconfig.json

download

{
    "compilerOptions": {
        "lib": ["ES2015"],
        "module": "commonjs",
        "outDir": "dist",
        "sourceMap": true,
        "strict": true,
        "target": "es2015"
    },
    "include": [
        "src"
    ]
}

可以自己新建并配置,或者使用命令初始化,处于typescript目录下,运行以下命令

./node_modules/.bin/tsc --init

基本配置项目说明:

  • include ts文件在哪个文件夹中
  • lib 运行环境包括哪些api
  • module ts代码编译成什么模块系统
  • outDir 编译后的js代码存放位置
  • stirct 是否开启严格模式
  • target ts编译成js的标准
  • … 有很多配置项具体可以查看其它资料

5、配置tslint.json

download

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "no-console": false
    },
    "rulesDirectory": []
}

可以自己新建并配置或者使用命令初始化,处于typescript目录下,运行以下命令

./node_modules/.bin/tslint --init

6、在src目录中创建index.ts文件并输入内容

download

mkdir src
touch src/index.ts

现在整体目录如下

download

typescript
----node_modules/
----src/
    ----index.ts
----package.json
----tsconfig.json
----tslint.json
index.ts
...
console.log("hello TypeScript")

7、编译

./node_modules/.bin/tsc

这时候文件夹中就会生成 dist/index.js

8、运行

node ./dist/index.js

如果中断输出“hello Typescript“那么说明我们第一个typescript项目配置成功

it/node/createtypscriptproject.1650720203.txt.gz · 最后更改: 2022-04-23 13:23 由 goldentianya
回到顶部
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0