当前位置: 移动技术网 > IT编程>脚本编程>NodeJs > 手把手教你使用TypeScript开发Node.js应用

手把手教你使用TypeScript开发Node.js应用

2019年07月19日  | 移动技术网IT编程  | 我要评论

为什么要使用typescript?

为了减少代码编写过程中出现的错误,以及更好的维护你的项目,本文将手把手教你配置一个简单的开发环境来编写node.js的应用程序,创建这样的一个开发环境有很多方式,这只是其中一种,希望对你有所帮助!

手把手教你使用typescript开发node.js应用

首先配置package.json

因为要在项目中使用webpack,所以首先得创建一个package.json文件,我们可以使用npm init来生成

{ 
 "name": "start", 
 "version": "1.0.0", 
 "description": "", 
 "main": "index.js", 
 "scripts": { 
 "test": "echo "error: no test specified" && exit 1" 
 }, 
 "author": "", 
 "license": "isc" 
} 

后面用到其他的在添加

开始

我们在项目的根目录创建一个src目录,添加一个main.js和information-logger.js文件,我们先使用javascript来创建:

// src/information-logger.js 
const os = require('os'); 
const { name, version} = require('../package.json'); 
module.exports = { 
 logapplicationinformation: () => 
 console.log({ 
 application: { 
 name, 
 version, 
 }, 
 }), 
 logsysteminformation: () => 
 console.log({ 
 system: { 
 platform: process.platform, 
 cpus: os.cpus().length, 
 }, 
 }), 
}; 
// src/main.js 
const informationlogger = require('./information-logger'); 
informationlogger.logapplicationinformation(); 
informationlogger.logsysteminformation(); 

我们先运行一下:node main.js(先到src目录下),打印了我的笔记本电脑的信息

webpack

首先第一件事就是要配置webpack的依赖项,记得用下面的命令,带上 -d,因为我们只在开发环境下

npm i -d webpack webpack-cli 

我们没用到webpack-dev-server,安装完成后我们创建webpack.config.js的配置文件

'use strict'; 
module.exports = (env = {}) => { 
 const config = { 
 entry: ['./src/main.js'], 
 mode: env.development ? 'development' : 'production', 
 target: 'node', 
 devtool: env.development ? 'cheap-eval-source-map' : false, 
 }; 
return config; 
}; 

最开始我们没那么多的配置需要配置。我们要使用它,先改一下package.json

“scripts”:{  
 “start”:“webpack --progress --env.development”, 
 “start :prod”:“webpack --progress”  
 }, 

然后我们就可以通过任一命令(npm start)来构建应用程序,它会创建一个dist/main.js,我们可也使用webpack.config.js指定输出不同的名称,现在的目录结构应该如下

nodemon

为什么不用webpack-dev-server,是因为没法用,所以可以使用nodemon来解决,它可以在我们开发期间重新启动node.js的应用程序,一样我们先来安装,依然需要 -d

npm i -d nodemon-webpack-plugin 

然后重新配置webpack.config.js

// webpack.config.js 
'use strict'; 
const nodemonplugin = require('nodemon-webpack-plugin'); 
module.exports = (env = {}) => { 
 const config = { 
 entry: ['./src/main.js'], 
 mode: env.development ? 'development' : 'production', 
 target: 'node', 
 devtool: env.development ? 'cheap-eval-source-map' : false,  
 resolve: { // tells webpack what files to watch. 
 modules: ['node_modules', 'src', 'package.json'], 
 },  
 plugins: [] // required for config.plugins.push(...); 
 }; 
if (env.nodemon) { 
 config.watch = true; 
 config.plugins.push(new nodemonplugin()); 
 } 
return config; 
}; 

webpack 监视配置将在我们更改文件时重建应用程序,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" 
 }, 

使用typescript

先安装依赖项

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

ts-loader(ts加载器)

因为要用ts-loader webpack插件来编译我们的typescript,所以得让webpack知道我们是使用了ts-loader插件来处理typescript文件的,更新之前的webpack.config.js

// webpack.config.js 
 'use strict'; 
const nodemonplugin = require('nodemon-webpack-plugin'); 
module.exports = (env = {}) => { 
 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(...); 
 }; 
if (env.nodemon) { 
 config.watch = true; 
 config.plugins.push(new nodemonplugin()); 
 } 
return config; 
}; 

tsconfig.json

typescript的配置文件

// 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"] 
} 

然后更改下之前创建的js文件扩展名

// information-logger.ts 
import os from 'os'; 
import { name, version } from '../package.json'; 
export class informationlogger { 
 static logapplicationinformation(): void { 
 console.log({ 
 application: { 
 name, 
 version, 
 }, 
 }); 
 } 
static logsysteminformation(): void { 
 console.log({ 
 system: { 
 platform: process.platform, 
 cpus: os.cpus().length, 
 }, 
 }); 
 } 
} 
// main.ts 
import { informationlogger } from './information-logger'; 
informationlogger.logapplicationinformation(); 
informationlogger.logsysteminformation(); 

现在目录结构应该是这样的

总结

我们可以使用多种方式来创建typescript的nodejs应用,不必拘泥于这一种,而且可能会有人并不赞同,因为typescript比纯javascript更需要花费更多精力,不过在新项目中,你仍然可以尝试这种方式,如果你有什么好的建议,欢迎在评论区留下你的意见!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网