开发环境

Web开发环境

客户侧开发工具

Understanding client-side web development tools - Learn web development | MDN (mozilla.org)

客户侧框架

Introduction to client-side frameworks - Learn web development | MDN (mozilla.org)

FrameworkBrowser supportPreferred DSLSupported DSLs
AngularIE9+TypeScriptHTML-based; TypeScript
ReactModern (IE9+ with Polyfills)JSXJSX; TypeScript
VueIE9+HTML-basedHTML-based, JSX, Pug
EmberModern (IE9+ in Ember version 2.18)HandlebarsHandlebars, TypeScript

服务侧框架

Server-side website programming - Learn web development | MDN (mozilla.org)

Express/Node introduction - Learn web development | MDN (mozilla.org)

Node.js

安装Node.js

Node.js® 是一个基于 Chrome V8引擎 的 JavaScript 运行时环境。

The runtime is intended for running directly on a computer or server OS. As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.maxogden/art-of-node: a short introduction to node.js (github.com)

Linux
# Using Ubuntu
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
apt-get install -y nodejs
# CentOS/Fedora
curl -fsSL https://rpm.nodesource.com/setup_lts.x | bash -
yum install -y nodejs
yum install gcc-c++ make # to compile&install native addons from npm*

*:或者执行yum groupinstall 'Development Tools'

Latest LTS Version: 16.17.0 (includes npm 8.15)。

Linux版本:https://github.com/nodesource/distributions/blob/master/README.md。

Windows版本:https://nodejs.org/en/download/。

Windows
winget install OpenJS.NodeJS.LTS  # v16 *

winget安装包无法自动安装Python和C++编译工具,需要从官网下载安装包并修改安装。

MSBUILD : error MSB4132: 无法识别工具版本“2.0”。可用的工具版本为 "4.0"。

包管理器

NPM

NPM (Node package manager)包含在Node.js中。

npm -l             # display usage info for all commands
npm <command> -h   # quick help on <command>
npm help <command> # show help in browser
初始化项目

为项目创建配置文件package.json(交互式):

cd progdir && npm {init|create}   # create<->init
# package name: (test-api)
# version: (1.0.0)
# description: coding a fun API using Express, a NodeJS minimalist web framework.
# entry point: (index.js)
# test command:
# git repository:
# keywords: express, api, nodejs
# author: Gary Wang
# license: (ISC)
mkdir src && touch src/index.js

配置文件内容包括:项目基本信息、执行脚本、依赖库声明。

{
    "name": "node-echo",     
    "main": "./lib/echo.js", // 包的主模块
    "dependencies": {
        "argv": "0.0.2"      // 依赖库名称和版本
    }
}
包管理

也可在npm (npmjs.com)搜索包。

安装/更新依赖库:

npm install       # 安装当前项目所需依赖(package.json)
           --location=global,user,project #*
           --global
npm install <foo> <bar@version> # 安装指定模块**
            --save # 将安装的模块加入package.json
npm update        # 更新满足条件的依赖库并更新(package-lock.json)
npm run <script>  # 运行package.json中定义的脚本
npm start|restart|stop --if-present   # => npm run start 

相应脚本需要在配置文件中定义,--if-present仅在相应命令存在的情况下执行而不产生错误。

*:安装位置:

  • global~\AppData\Roaming\npm\node_modulesWindows)或/usr/local/nodejs/lib/node_modules/(Linux);
  • user~\node_modules
  • projectPROJECT_HOME\node_modules

**:如果当前目录下没有项目配置文件(package.json),执行命令时会自动生成包含所安装包的配置文件。

仓库镜像配置

默认仓库为https://registry.npmjs.org/,可修改为国内镜像源(阿里云:https://registry.npmmirror.com

npm config set registry https://registry.npmmirror.com
npm config get registry
包管理

Java Script包采用语义化版本控制,以在项目中使用依赖包时保证良好的兼容性。项目使用的依赖包声明方式:

  • 仅允许patch版本升级:1.0, 1.0.x, ~1.0.4
  • 允许minorpatch版本升级:1, 1.x, ^1.0.4
  • 允许major版本升级:*, x
  • 版本范围:>2.11.0.0 - 1.2.0(可使用>,<,>=,<=,=-表示范围)。
  • 组合:^2 <2.2 || >2.3
安装全局工具
npm install --global,-g <module-name>

yarn

curl -sL https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo
yum install yarn
NODE_ENV=prodution yarn start --production

pnpm

模块编译

node-gypMSBuild.exe failed with exit code: 1解决方法

npm install --ignore-scripts
npm rebuild node-sass --force --ignore-scripts

Node运行环境管理

nvm version                   # 查看nvm版本
nvm arch                      # 查看node运行的系统架构
nvm current                   # 当前激活的node版本
nvm list [available]          # 列出已安装/可安装版本
nvm install <version> [32|64] # 安装指定版本node*
nvm use [version] [32|64]     # 切换版本(全局生效)**
nvm uninstall <version>       # 必须指定具体版本

*:具体版本号、ltslatest

**:需要管理员权限创建符号链接。

下载镜像
nvm proxy [URL]
nvm node_mirror [URL] # -> 下载node地址:https://nodejs.org/dist/
nvm npm_mirror [URL]  # -> 下载NPM地址:https://github.com/npm/cli/archive/
nvm root [PATH]       # -> 环境安装目录:~\AppData\Roaming\nvm

Node交互式环境

在终端执行node进入交互命令行。

console.log('hello world!')

Node.js库

HTTP服务

const http = require("http");
const hostname = "127.0.0.1", port = 5000;
const server = http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
});
server.listen(port, hostname, function () { // start server
    console.log(`Server running at http://${hostname}:${port}/`);
})

Node.js应用程序

npx <package>  # -> x, npm exec

http-server

http-server is a simple, zero-configuration command-line static HTTP server. It is powerful enough for production usage, but it's simple and hackable enough to be used for testing, local development and learning.

用法
http-server [./public]  # 如果"./public"不存在则默认为"./" 
            -p,--port=8080
            -a 0.0.0.0
            --cors=false
            -o [path]   # 在浏览器中打开指定路径
            --username USER
            --password
            -S,--tls,--ssl -C,--cert=cert.pem -K,--key=key.pem

Web前端打包

将HTML文件引用的NPM包及其依赖库打包到单一文件,方便引用。

browserify

npm install -g browserify

browserify/browserify: browser-side require() the node.js way (github.com)

browserify.cmd .\index.js  --outfile .\bundle.js 

--outfile:在Windows终端中执行命令,如果将输出定向到文件可能导致编码不匹配的问题(输出内容为UTF-8,而终端编码为UTF-16)从而导致乱码。使用该选项打开文件进行输出可避免该问题。

webpack

internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.

打包配置webpack.config.js

const path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

引用打包后的文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    ...
  </head>
  <body>
    ...
    <script src="dist/bundle.js"></script>
  </body>
</html>

Installation | webpack

webpack

esbuild

npm install -g esbuild
esbuild app.jsx --bundle --outfile=out.js

esbuild - Getting Started

TypeScript

TypeScript is available as a package on the npm registry available as "typescript".

npm install typescript --save-dev # install for current project
npm install -g typescript         # Globally Installing TypeScript

codebases should prefer a project-wide installation over a global install so that they can benefit from reproducible builds across different machines.

TypeScript: Bootstrapping tools for TypeScript projects (typescriptlang.org)

编译

将TypeScript源码转换为JavaScript。

  • Erased Types
  • Downleveling
  • Strictness

编译项目

npx tsc --init                 # 初始化项目,生成tsconfig.json
npx tsc                        # 编译项目
tsc -p ./path/to/tsconfig.json # 编译指定路径下的项目
npx tsc program.ts utils.ts    # 编译源码,忽略项目配置

Express

Fast, unopinionated, minimalist web framework for Node.js.

Express封装了Node.js的httphttps,并提供高层次的HTTP处理接口,如处理不同的HTTP方法、API路由、服务静态文件和基于模板创建动态响应。

  • Robust routing
  • Focus on high performance
  • Super-high test coverage
  • HTTP helpers (redirection, caching, etc)
  • View system supporting 14+ template engines
  • Content negotiation
  • Executable for generating applications quickly

Express项目

使用模板快速开始构建App。

npm install -g express-generator@4
express /project/folder  # "npx express-generator" for Node.js 8.2+
npm install
npm start   # -> http://localhost:3000

项目目录结构如下:

/project/folder
├─bin
├─public
│  ├─images
│  ├─javascripts
│  └─stylesheets
├─routes
└─views

创建新项目并添加express库。

npm init && npm install express

代码结构

const express = require('express')  // 导入express库
const app = express()               // 创建应用实例
const port = 5000
// 定义API和处理方法
app.get('/', (req, res) => {
    res.send('hello world!');
})
// 启动服务
app.listen(port, () => {
    console.log(`Example app listening on port ${port}.`);
})

监听多个端口与协议:

const http = require('http'),
      https = require('https'),
      express = require('express'),
      app = express();
http.createServer(app).listen(80); 
https.createServer({options}, app).listen(443);

Express examples (expressjs.com)

Express Tutorial: The Local Library website - Learn web development | MDN (mozilla.org)

Express/Node introduction - Learn web development | MDN (mozilla.org)

URL处理函数

一个URL可定义多个匹配的处理函数。

app.METHOD(PATH, HANDLER)
  • METHOD是HTTP方法;
  • PATH是服务器的URL;
  • HANDLER是处理函数。
req
res

服务静态文件

express.static(root, [options])
app.use(express.static('public'))  // 添加多个静态文件目录
app.use(express.static('files'))   // 按顺序查找静态资源
app.use('/static', express.static('public'))  // 为静态资源URL添加前缀

root指定服务器上存放静态文件的根目录(可为绝对或相对路径,该目录名称不是URL的一部分)。

使用反向代理提高静态资源的服务效率。

API路由

app.use('BASE_URL', Router)

服务静态文件

错误处理

使用数据库

Angular

Angular是一个用HTML和TypeScript构建客户端应用的平台与框架。

  • 模块NgModule;根模块AppModule提供了用来启动应用的引导机制。
  • 组件@Component():每个应用至少有一个组件(根组件),它会把组件树和页面中的DOM连接起来。每个组件都会定义一个类,其中包含应用的数据和逻辑,并与一个HTML模板相关联,该模板定义了一个供目标环境下显示的视图。
  • 模板:模板中的指令会提供程序逻辑,而绑定标记会把你应用中的数据和 DOM 连接在一起。
  • 服务类:与特定视图无关并希望跨组件共享的数据或逻辑,通过@Injectable()让服务作为依赖被注入到客户组件中。
  • 路由:

overview

使用 Angular CLI 来创建最初的应用程序。

Angular命令行工具

安装和卸载命令行工具
npm install -g @angular/cli			# sudo on Ubuntu
npm uninstall -g @angular/cli
npm cache clean --force

Windows上使用PowerShell需要修改脚本执行策略:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
创建新项目
ng new my-app
npm install --legacy-peer-deps # 如果安装依赖出错使用该命令
编译项目
ng build
启动应用
ng serve --host=ws-gary --port port --ssl [--disableHostCheck]

项目结构

package.json:包含了项目的配置文件,包括项目名称、描述、源代码仓库、版本、许可证、项目构建、测试、启动命令、依赖包等信息。

angular.json:Angular框架配置文件。

tsconfig.json:TypeScript配置文件。

编译

ng update		# shou packages can be updated
ng update --all [--allow-dirty] [--force]
ng update @angular/core @angular/cli

Electron

Electron is a framework for building desktop applications using JavaScript, HTML, and CSS. By embedding Chromium and Node.js into its binary, Electron allows you to maintain one JavaScript codebase and create cross-platform apps that work on Windows, macOS, and Linux — no native development experience required.

git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install && npm start

This tutorial will guide you through the process of developing a desktop application with Electron and distributing it to end users.

开发工具

VS Code

调试

VS Code支持在浏览器中启动服务并调试Javascript程序,或通过Node.js执行环境进行调试。