安装NodeJS和TypeScript简要指南
在ubuntu上安装NodeJS
安装
方法 1:使用 Ubuntu 默认仓库安装
sudo apt update && sudo apt upgradesudo apt install nodejssudo apt install npmnode -v
#v22.16.0
方法 2:使用 nvm(Node Version Manager)安装–推荐
nvm 允许在同一台机器上管理多个 Node.js 版本,非常适合需要在不同版本间切换的开发者。
nvm项目地址:https://github.com/nvm-sh/nvm
安装nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
或者
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
卸载 Node.js
apt 安装的卸载方法:
如果您是通过 apt 安装的 Node.js,可以使用以下命令卸载:
sudo apt remove nodejs
如果您想同时删除配置文件,请使用:
sudo apt purge nodejs
nvm 安装的卸载方法:
如果您是通过 nvm 安装的 Node.js,可以使用以下命令卸载特定版本:
nvm uninstall node_version
在Windows上安装NodeJS
可以在以下网址https://github.com/coreybutler/nvm-windows/releases 下载 nvmsetup.zip。
安装完成后。 打开 PowerShell,尝试使用 nvm-windows 来列出当前安装的 Node 版本(此时应为无):nvm ls
nvm ls
No installations recognized.
安装完成后:
nvm ls* 24.2.0 (Currently using 64-bit executable)
安装当前版本的 Node.js:nvm install latest
nvm install latest
24.2.0
Downloading node.js version 24.2.0 (64-bit)...
Extracting node and npm...
Complete
Installation complete.
If you want to use this version, type:nvm use 24.2.0
安装所需的 Node.js 版本号后,输入 nvm use <version>
(将 <version>
替换为数字,即:nvm use 24.2.0
),选择要使用的版本。
若要更改要用于项目的 Node.js 版本,需创建新的项目目录 mkdir NodeTest
,然后进入目录 cd NodeTest
,然后输入 nvm use <version>
将 <version>
替换为要使用的版本号。
验证安装的 npm 版本:npm --version
,这个版本号将自动更改为与当前 Node.js版本相关的 npm 版本。
使用nvm
以下为在linux使用的指令,在windows中有些不同。
source ~/.bashrc#If you want to see what versions are available to install:
nvm ls-remote#If you want to see what versions are installed:
nvm ls#And then in any new shell just use the installed version:#install a spesific version
nvm install v22.16.0nvm use node
#Or you can just run it:nvm run node --version#You can also get the path to the executable to where it was installed:nvm which 12.22#To set a default Node version to be used in any new shell, use the alias 'default':nvm alias default node # this refers to the latest installed version of node
nvm alias default 18 # this refers to the latest installed v18.x version of node
nvm alias default 18.12 # this refers to the latest installed v18.12.x version of nodenode -v
安装Typescript
确认已安装NodeJS
更新NPM到最新版本
sudo npm install npm@latest -g
安装TypeScript编译器
sudo npm install -g typescript
验证TypeScript 安装
$ tsc --version
Version 5.8.3
创建TypeScript测试项目
Step 1: 创建项目目录
mkdir ts-test-project
cd ts-test-project
Step 2: 初始化一个TypeScript 项目
tsc --init
# creates a tsconfig.json file with:
target: es2016module: commonjsstrict: trueesModuleInterop: trueskipLibCheck: trueforceConsistentCasingInFileNames: trueYou can learn more at https://aka.ms/tsconfig
Step 3: 创建一个简单的 TypeScript 文件
nano hello.tslet message: string = "Hello, World!";
console.log(message);
Step 4: 编译和运行这个TypeScript 文件
tsc hello.ts
#compile the hello.ts file into a JavaScript file named hello.js
使用Node.js运行编译后的文件:
node hello.js