从0创建一个nodejs项目
环境搭建
开发环境
使用win10操作系统,
使用vscode进行代码的编写和测试
安装必要的工具
- 下载并安装好nodejs, nodejs官网 https://nodejs.org/en/
注意安装时可以选择选项安装一些常用的库,并且在PATH中加入nodejs路径(安装nodejs时注意勾选)
安装完成后,打开命令行,
输入命令 node -v, 如果安装正确,会显示当前安装的node版本号
输入命令 npm -v, 如果安装正确,会显示当前安装的npm版本号
npm是一个nodejs常用的包管理器,可以用来管理项目中使用的一些外部库, 大大加快开发的进度,安装node时会将npm一起安装好
- 安装TypeScript
使用刚刚安装好的npm工具进行安装
在命令行中输入命令 npm install -g typescript,
如果安装正确,输入 tsc -v, 会显示当前typescript的版本号
环境搭建完成后,就可以开始创建新项目了
建立一个简单的nodejs项目
- 在工作文件夹中,新建文件夹,重命名为Demo,作为测试项目,比如 D:\workspace\TSProject\Demo
- 打开命令行,进入Demo文件夹下
- 使用命令 npm init 创建项目,根据提示,输入项目名称,版本,作者等, 系统会生产一个package.json的文件,作为这个项目最基本的描述
- 要使用TypeScript作为开发语言, 使用命令 tsc --init 来初始化ts的配置,运行后,项目文件夹中出现一个 tsconfig.json 的文件,文件的各个字段定义请参考 tsconfig.json
通常将项目的源文件目录设置为 “./src” 输出目录设置为 “./dist”,我们就可以在src目录中编写ts文件,然后文件经过编译和转换后,会在dist中生成输出文件
我使用的文件内容如下
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": false, /* Enable strict null checks. */
"strictFunctionTypes": false, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
"inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
- 在Demo文件夹中创建 src 和 dist 文件夹, 并在src文件夹中,创建一个app.ts文件,作为项目的入口文件,并写入以下代码
console.log("demo test")
- 使用tsc命令,将ts文件编译成js文件,编译完成后,在dist目录中会出现src中对应的文件,但是扩展名变成.js
- 使用命令 node ./dist/app.js 运行生产的js文件,运行结果,屏幕中输出 demo test
使用ts-node 直接运行ts文件
如果在开发阶段,每次修改代码后,都重新生产js文件确实比较麻烦,我们可以使用ts-node,来直接运行ts文件进行项目的开发测试
- 安装ts-node, 使用命令 npm install ts-node -g 全局安装ts-node
- 使用vscode的调试功能, 在 .vscode 文件夹中创建launch.json 文件,使用如下配置
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "launch ts-node",
"runtimeArgs": [
"--nolazy",
"-r",
"C:/Users/zhang/AppData/Roaming/npm/node_modules/ts-node/register"
],
"args": [
"${workspaceFolder}/src/app.ts"
],
"sourceMaps": true,
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_ENV": "dev",
"LOG_LEVEL": "trace"
}
}
]
}
在调试界面运行项目,就可以正常进行项目的运行和调试,可以直接在ts文件中打断点
结束
至此,一个最简单的nodejs项目已经创建完成了