從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項目已經創建完成了