前言

第一篇中,我们简单介绍了TypeScript的一些简单语法,那么如果我们只是简单使用TypeScript开发一个web项目,应该做哪些准备?接下来我们就结合TypeScript和Webpack来创建一个基于TypeScript的Web应用程序。

准备工作

为了创建第一个Web应用,我们先做一些基本的准备工作,需要安装以下依赖:

webpack

webpack-cli

webpack-dev-server

webpack-merge

html-webpack-plugin

clean-webpack-plugin

typescript

ts-loader

jest & @types/jest

创建项目

新建文件夹ts-init,npm init -y初始化package.json文件。

之后,我们依次安装上述依赖到项目中,以下是安装之后的package.json文件:

{
  "name": "ts-init",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.ts",   // 设置入口文件
  "scripts": {
    "start": "webpack-dev-server --mode=development --config ./build/webpack.config.js",  //设置启动命令
    "build": "webpack --mode=production --config ./build/webpack.config.js",  // 配置build命令
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^24.0.18",
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^24.9.0",
    "ts-jest": "^24.0.2",
    "ts-loader": "^6.0.4",
    "typescript": "^3.5.3",
    "webpack": "^4.39.2",
    "webpack-cli": "^3.3.7",
    "webpack-dev-server": "^3.8.0",
    "webpack-merge": "^4.2.1"
  }
}

接下来我们按照package.json创建src和build目录,目录结构如下:

让我们引入来创建webpack文件,我们创建在build目录下面。

为了保证我们可以按照develop和production方式来编译,我们创建了四个个webpack文件,如下所示

其中,主配置文件为webpack.config.js:

const merge = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const devConfig = require('./webpack.dev.config')
const proConfig = require('./webpack.pro.config')

// const config = process.env.NODE_ENV === 'development' ? devConfig : proConfig

module.exports = (env, argv) => {
    let config = argv.mode === 'development' ? devConfig : proConfig; // 通过不同的环境,我们运行不同的webpack文件
    return merge(baseConfig, config);
};

提取的基础配置为webpack.base.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: {
        'app': './src/index.ts'   // 入口文件
    },
    output: {
        filename: '[name].[chunkhash:8].js' // 编译的文件以名字.hash值结尾
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/i,
                use: [{
                    loader: 'ts-loader'
                }],
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'    // 启动HTML文件
        })
    ],
    optimization: { // 简单拆包
        splitChunks: {
            chunks: 'all'
        }
    }
}

开发环境配置为webpack.dev.config.js:

module.exports = {
    devtool: 'cheap-module-eval-source-map' // 开发环境我们只添加  忽略列信息的ts源码的sourcemap
}

生产环境配置为webpack.pro.config.js:

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    plugins: [
        new CleanWebpackPlugin()  // 生产环境我们只先添加build清除文件,用来清除每次build产生的hash文件,避免因为无用文件导致打包过大
    ]
}

接下来,我们在src文件夹下编写HTML文件模板,我们创建一个div用来承载单页应用的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TypeScript</title>
</head>
<body>
    <div class="app"></div>
</body>
</html>

我们src文件夹下面简单编写一个index.ts文件,写入hello world程序

let str: string = 'Hello TypeScript'
document.querySelectorAll('.app')[0].innerHTML = str

ok,一切工作都已经准备完毕,一个ts编写的web程序基本项目已经被我们创建

运行

在命令行我们输入:npm start命令,程序默认运行路径为:http://localhost:8080/,我们在自己浏览器打开网址,发现我们的程序运行成功了:

添加Jest单元测试

现在为我们的项目添加简单的单元测试。

我们首先在src模块下面创建一个普通的模块math.ts,里面包括加法和减法两个方法,我们将会对这两个方法做简单的单元测试:

function add(a: number, b: number) {
    return a + b;
}

function sub(a: number, b: number) {
    return a - b;
}

module.exports = {
    add,
    sub
}

接下来我们在test文件夹下创建测试文件math.test.ts:

const math = require('../src/math');

test('add: 1 + 1 = 2', () => {
    expect(math.add(1, 1)).toBe(2);
})

test('sub: 10 - 1 = 9', () => {
    expect(math.sub(10, 1)).toBe(8);
})

我们运行test命令:npm test,运行结果如下:

由上报错可知,我们test文件写错了,10 -1我们写成了希望=8,我们修改一下test文件:

const math = require('../src/math');

test('add: 1 + 1 = 2', () => {
    expect(math.add(1, 1)).toBe(2);
})

test('sub: 10 - 1 = 9', () => {
    expect(math.sub(10, 1)).toBe(9);  // 修改成9
})

继续运行npm test:

由上可知,我们测试通过了。

到此为止,我们的一个简单地可用TypeScript项目开发的Web程序就创建完毕了。

结尾

TypeScript应用非常简单,我们只需要做简单的配置,就可以让项目运行起来,TypeScript的类型系统会帮助我们做类型检查,减少我们的边界值错误几率,可以大大增强我们的开发体验。

同时,TypeScript的测试也很简单,用Jest我们可以做到对项目的单元测试,使我们的代码更可靠和更安全。

简单的项目已经被我上传至github:https://github.com/qixingduanyan/ts-web

 

131 thoughts on “深入浅出TypeScript(2)- 用TypeScript创建web项目

  1. PhillipSwark说道:

    You actually reported it effectively. what is cbd oil

  2. Larrylubre说道:

    Truly all kinds of amazing info. sertraline hcl

  3. Richardundip说道:

    Really quite a lot of amazing material. hemp oil vs cbd oil

  4. Larrylubre说道:

    You actually reported that very well. canada drugs

  5. PhillipSwark说道:

    You actually expressed it fantastically! benefits of cbd oil drops

  6. TyroneMerne说道:

    Incredible many of very good info! what is cbd oil

  7. Richardundip说道:

    Really quite a lot of helpful data! viagra 100mg

  8. ErnestCunda说道:

    You actually said this really well. zestril

  9. Larrylubre说道:

    You stated this exceptionally well. Motilium France

  10. ErnestCunda说道:

    You actually explained it very well! furosemida

  11. Richardundip说道:

    Really plenty of helpful material! hemp oil benefits

  12. TyroneMerne说道:

    Good forum posts. Appreciate it. viagra online

  13. Louiscoutt说道:

    Incredible all kinds of wonderful data. Cialis 20mg Veron Pharma

  14. TyroneMerne说道:

    Incredible loads of good knowledge. canadian drugs

  15. Louiscoutt说道:

    Appreciate it! Loads of information.
    canadianpharmacy

  16. Larrylubre说道:

    Really a good deal of very good tips! zestoretic

  17. ErnestCunda说道:

    Whoa a good deal of valuable material. cephalexin 500 mg

  18. ErnestCunda说道:

    Many thanks, Excellent information. proventil inhaler

  19. ErnestCunda说道:

    You actually explained that exceptionally well. retin-a

  20. ErnestCunda说道:

    Many thanks. A good amount of posts!
    levitra 20 mg

  21. Larrylubre说道:

    Incredible a good deal of beneficial info. buy cialis

  22. Richardundip说道:

    Incredible a good deal of very good advice. cbd oil

  23. Larrylubre说道:

    You actually mentioned that wonderfully! glucophage xr 500

  24. Louiscoutt说道:

    Incredible many of helpful knowledge! canada pharmacy online

  25. Larrylubre说道:

    You suggested this superbly! phenergan

  26. Larrylubre说道:

    Incredible plenty of great material! Metformin In Kenya

发表评论