最近想用TypeScript
來重構(gòu)后臺送朱,由于Node
版本是8+
表谊,能夠直接支持async
、await
喉祭,于是乎就想直接轉(zhuǎn)換养渴,使用的tsconfig.json
內(nèi)容如下:
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017"
]
}
}
這么一看似乎沒問題,那么我們寫個例子來測試一下:
import * as Koa from 'koa';
const app: Koa = new Koa();
app.use(async (ctx: Koa.Context, next: () => Promise<any>) => {
await next();
});
app.use(async(ctx: Koa.Context, next: () => Promise<any>) => {
ctx.body = 'Hello There';
});
const port = 11001;
app.listen(port);
console.log(`在${port}監(jiān)聽`);
經(jīng)過轉(zhuǎn)換后的結(jié)果是:
import * as Koa from 'koa';
const app = new Koa();
app.use(async (ctx, next) => {
await next();
});
app.use(async (ctx, next) => {
ctx.body = 'Hello There';
});
const port = 11001;
app.listen(port);
console.log(`在${port}監(jiān)聽`);
看著似乎沒問題臂拓,但是仔細看還是有問題的厚脉,因為node8其實是不支持import
這樣的語法的。
那么怎么辦呢胶惰?
module
機智的我們可能回想起傻工,tsconfig.json
中其實有一項是配置模塊的類型的: module
而node
常用的就是commonjs
。
所以加上一句就可以了:
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"typeRoots": [
"node_modules/@types"
],
"module": "commonjs",
"lib": [
"es2017"
]
}
}
再次打包,就得到了我們想要的結(jié)果了:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Koa = require("koa");
const app = new Koa();
app.use(async (ctx, next) => {
await next();
});
app.use(async (ctx, next) => {
ctx.body = 'Hello There';
});
const port = 11001;
app.listen(port);
console.log(`在${port}監(jiān)聽`);
壓縮
這個OK了中捆,下一步優(yōu)化就是壓縮了鸯匹,似乎沒有問題了,但是當我們使用uglifyjs
去進行壓縮的時候泄伪,突然報了個錯:
GulpUglifyError: unable to minify JavaScript
無法壓縮殴蓬。
google
了一番,發(fā)現(xiàn)是uglify
不支持es2016
等蟋滴,所以需要先經(jīng)過babel轉(zhuǎn)換染厅,然后在Uglify
。
這就有點搞笑了津函,我本來就想用node8
的新特性肖粮,這么一轉(zhuǎn),豈不是回去了尔苦。
于是涩馆,搜索了一番,發(fā)現(xiàn)了uglify-es
插件允坚,這個插件專門就是解決這個問題了魂那,好了后臺問題暫時都解決了,接下來開始碼代碼了稠项。