express环境(开发和生产)配置

1,797 阅读3分钟

express环境(开发和生产)配置

可用git实现版本控制

npm init
npm install -g typescript
npm install typescript --save-dev
tsc --init
此时会多一个 `tsconfig.json` 档案,这个档案是用来设定编译选项的,这边提供我的配置给大家参考:
{
  "compilerOptions": {
    "incremental": true,               // 启用增量编译
    "target": "ES2017",                // 编译成指定的 JavaScript 版本
    "module": "commonjs",              // 指定编译成何种模组
    "declaration": true,               // 产生 '.d.ts' 档
    "sourceMap": true,                 // 产生 '.map' 档
    "outDir": "./dist",                // 指定编译后的档案存放点
    "rootDir": "./src",                // 载入点的位置
    "removeComments": true,            // 移除注解
    "strict": true,                    // 采用严格模式
    "baseUrl": "./src",                // 指定汇入档案的基准路径
    "esModuleInterop": true,           // 兼容模组
    "experimentalDecorators": true,    // 启用装饰器
    "emitDecoratorMetadata": true      // 提供装饰器 metadata
  },
  "include": ["src/**/*.ts"],          // 纳入编译范围
  "exclude": ["node_modules", "dist"]  //不纳入编译范围
}

npm install express
//取得 node.js 与 express 的 type 定义档,在开发时能够清楚知道有哪些功能可以使用:
npm install @types/node @types/express --save-dev

//新增 `index.ts`,将资料夹结构调整如下:
├── src
|   └── index.ts
├── package.json
└── tsconfig.json
//index.ts内容-------------------------
import express from 'express';

const app = express();

app.get('/', (req, res, next) => {
    res.send('Hello, World!!');
});

app.listen(3000, () => console.log('http server is running at port 3000.'));
//--------------------------------


//提示:没装过先装 
npm install -g ts-node
npm install -g typescript
//再装局部的:实现自启动
npm install ts-node --save-dev

//在 `package.json` 中的 `script` 栏位添加 `start` 项目:

"scripts": {
  "start:dev": "ts-node ./src/index.ts"
}

//启动项目
npm run start:dev

//输入[http://localhost:3000](http://localhost:3000/)来检视结果

image.png

编译

那要如何对专案进行编译呢?毕竟 ts-node 并不适合用在正式环境中,还是需要编译成 JavaScript 再透过 node.js 来启动,所以修改一下 package.json 的内容:

"scripts": {
  "start": "npm run build && node ./dist/index.js",
  "start:dev": "ts-node ./src/index.ts",
  "build": "tsc"
}

每次要编译并启动正式环境就执行:

npm start

其原理很简单,根据专案的 tsconfig.json 进行编译,完成后再透过 node.js 来启动。

自动化

在开发阶段的启动方式有个小问题,就是每当更改程式码的时候,它并 不会自动刷新,需要关掉以后再执行一次npm run start:dev,身为一个 IT 人怎么可以忍受这种事情!所以我们要透过强大的nodemon来解决:

npm install nodemon --save-dev

安装完毕后,去更改 package.json 的配置:

"scripts": {
  "start": "npm run build && node ./dist/index.js",
  "start:dev": "nodemon --exec ts-node ./src/index.ts",
  "build": "tsc"
}

如此一来,只需要执行一次 npm run start:dev 就可以了,不必每次更改程式码就执行一次,是不是很方便呢!

环境变数

那如果想要让 开发环境 (development) 跟 正式环境 (production) 用不同的环境变数要怎么做呢?这时候我们就需要使用dotenv来管理环境变数:

npm install dotenv -g
npm install -g cross-env –save-dev

我们将环境变数的档案分成 development.env 与production.env,并调整专案结构:

.
├── src
|   ├── index.ts
|   └── environments
|       ├── development.env
|       └── production.env
├── package.json
└── tsconfig.json

development.env的内容:

PORT=3000

production.env的内容:

PORT=8080

接着透过 npm 的脚本传入参数来指定现在的环境是 development 还是 production:

 "scripts": {
    "start": "npm run build && cross-env NODE_ENV=production node ./dist/index.js",
    "start:dev": "nodemon --exec cross-env NODE_ENV=development ts-node ./src/index.ts",
    "build": "tsc"
  },

最后就是去调整 index.ts 的内容,透过 NODE_ENV 参数与 dotenv 来选定环境变数:

import express from 'express';
import path from 'path';
import dotenv from 'dotenv';

const app = express();

// 动态选择环境变数的档案
dotenv.config({ path: path.resolve(__dirname, `./environments/${ process.env.NODE_ENV }.env`) });

app.get('/', (req, res, next) => {
    res.send('Hello, World!!');
});

app.listen(process.env.PORT, () => console.log(`http server is running at port ${ process.env.PORT }.`));

如果使用 git 的话,建议 env 档案都不要 commit,通常 env 里面会放一些敏感资讯,如:资料库的密码。