手把手教你使用TypeScript開(kāi)發(fā)Node.js應(yīng)用
為什么要使用TypeScript?
為了減少代碼編寫過(guò)程中出現(xiàn)的錯(cuò)誤,以及更好的維護(hù)你的項(xiàng)目,本文將手把手教你配置一個(gè)簡(jiǎn)單的開(kāi)發(fā)環(huán)境來(lái)編寫Node.js的應(yīng)用程序,創(chuàng)建這樣的一個(gè)開(kāi)發(fā)環(huán)境有很多方式,這只是其中一種,希望對(duì)你有所幫助!
手把手教你使用TypeScript開(kāi)發(fā)Node.js應(yīng)用
首先配置package.json
因?yàn)橐陧?xiàng)目中使用Webpack,所以首先得創(chuàng)建一個(gè)package.json文件,我們可以使用npm init來(lái)生成
- {
- "name": "start",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo "Error: no test specified" && exit 1"
- },
- "author": "",
- "license": "ISC"
- }
后面用到其他的在添加
開(kāi)始
我們?cè)陧?xiàng)目的根目錄創(chuàng)建一個(gè)src目錄,添加一個(gè)main.js和information-logger.js文件,我們先使用Javascript來(lái)創(chuàng)建:
- // 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();
我們先運(yùn)行一下:node main.js(先到src目錄下),打印了我的筆記本電腦的信息:
Webpack
首先***件事就是要配置Webpack的依賴項(xiàng),記得用下面的命令,帶上 -d,因?yàn)槲覀冎辉陂_(kāi)發(fā)環(huán)境下 :
- npm i -D webpack webpack-cli
我們沒(méi)用到webpack-dev-server,安裝完成后我們創(chuàng)建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;
- };
最開(kāi)始我們沒(méi)那么多的配置需要配置。我們要使用它,先改一下package.json :
- “scripts”:{
- “start”:“webpack --progress --env.development”,
- “start :prod”:“webpack --progress”
- },
然后我們就可以通過(guò)任一命令(npm start)來(lái)構(gòu)建應(yīng)用程序,它會(huì)創(chuàng)建一個(gè)dist/main.js,我們可也使用webpack.config.js指定輸出不同的名稱,現(xiàn)在的目錄結(jié)構(gòu)應(yīng)該如下:
nodemon
為什么不用webpack-dev-server,是因?yàn)闆](méi)法用,所以可以使用nodemon來(lái)解決,它可以在我們開(kāi)發(fā)期間重新啟動(dòng)Node.js的應(yīng)用程序,一樣我們先來(lái)安裝,依然需要 -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 監(jiān)視配置將在我們更改文件時(shí)重建應(yīng)用程序,nodemon在我們構(gòu)建完成重新啟動(dòng)應(yīng)用程序,需要重新配置下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
先安裝依賴項(xiàng):
- npm i -D typescript ts-loader @types/node@^10.0.0
ts-loader(ts加載器)
因?yàn)橐胻s-loader Webpack插件來(lái)編譯我們的TypeScript,所以得讓W(xué)ebpack知道我們是使用了ts-loader插件來(lái)處理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"]
- }
然后更改下之前創(chuàng)建的js文件擴(kuò)展名:
- // 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();
現(xiàn)在目錄結(jié)構(gòu)應(yīng)該是這樣的
總結(jié)
我們可以使用多種方式來(lái)創(chuàng)建TypeScript的Nodejs應(yīng)用,不必拘泥于這一種,而且可能會(huì)有人并不贊同,因?yàn)門ypeScript比純Javascript更需要花費(fèi)更多精力,不過(guò)在新項(xiàng)目中,你仍然可以嘗試這種方式,如果你有什么好的建議,歡迎在評(píng)論區(qū)留下你的意見(jiàn)!