TypeScript开发Node.js程序的方法

2020-06-17 07:19:11易采站长站整理

},
plugins: [] // required for config.plugins.push(...);
};
if (env.nodemon) {
config.watch = true;
config.plugins.push(new NodemonPlugin());
}
return config;
};

当我们传递 nodemon 标志时,需要设置 Webpack watch config,并添加 nodemon 插件。当我们更改文件时,Webpack watch config 将会重建程序。 nodemon 插件会在重建完成后重新启动程序。

我们还需要更新 npm 命令。我还创建了一些没有 nodemon标志的构建命令,。


// package.json
...
scripts: [
"start": "webpack --progress --env.development --env.nodemon",
"start:prod": "webpack --progress --env.nodemon",
"build": "webpack --progress --env.development",
"build:prod": "webpack --progress",
"build:ci": "webpack"
],
...

我们完成了 Node.js 程序的基本 Webpack 设置。下一步是添加 TypeScript!

TypeScript

现在让我们添加 TypeScript!首先安装需要的依赖项。

由于这是一个 Node.js 项目,我们还需要安装相关的支持。我正在研究 Node.js 的 LTS 版本,也就是10 版。这就是我安装 ^ 10.0.0 版的原因。


npm i -D typescript ts-loader @types/node@^10.0.0

ts-loader

我们将用 ts-loader Webpack 插件来编译 TypeScript。

我们需要将 entry 文件的后缀更改为 .ts 并告诉 webpack 它还必须解析 .ts 文件(默认情况下,Webpack仅适用于 .js 文件)。


// webpack.config.js
...
const config = {
entry: ['./src/main.ts'],
mode: env.development ? 'development' : 'production',
target: 'node',
devtool: env.development ? 'cheap-eval-source-map' : false,
resolve: {
// Tells Webpack what files to watch
extensions: ['.ts', '.js'],
modules: ['node_modules', 'src', 'package.json'],
},
module: {
rules: [
{
test: /.ts$/,
use: 'ts-loader',
},
],
},
plugins: [], // Required for config.plugins.push(...);
};
...

tsconfig.json

如果现在尝试运行我们的程序,它将会崩溃。因为还缺少 tsconfig.json 文件。所以先创建一个。


// tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"lib": ["dom", "es2018"],
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"removeComments": true,
"resolveJsonModule": true,
"strict": true,
"typeRoots": ["node_modules/@types"] },
"exclude": ["node_modules"],
"include": ["src/**/*.ts"]}