如何使用TypeScript和Webpack编写网页应用

TypeScript所作的,是在JavaScript的基础上加入了类型,TypeScript编译器将TypeScript编译成JavaScript,能够在浏览器或者nodejs平台上运行。最新版本的TypeScript语法根ES6标准已经十分接近,并且由于是JS的超集,TS代码中夹杂普通JS代码也是能够的。因此,若是你也考虑开始使用Bable+ES6,不妨也看一下TypeScript。html

TypeScript项目和tsconfig.json

首先安装TypeScript编译器node

npm i -g typescript

进入项目目录,新建一个hello.tsjquery

function sayHello(name: string) {
    return 'Hello, ' + name;
}

let myName = 'Cheng Wang';

console.log(sayHello(myName));

而后执行webpack

tsc hello.ts

编译器会生成 hello.jsgit

function sayHello(name) {
    return 'Hello, ' + name;
}
var myName = 'Cheng Wang';
console.log(sayHello(myName));

为了方便编译器和编辑器识别TypeScript项目,TypeScript约定了tsconfig.json文件来存储项目配置,若是运行tsc时不指定输入文件,编译器则会查找项目目录中的这个文件,若是找不到则会依次向父级目录查找。好比这样:github

{
    "compilerOptions": {
        "outFile": "dist/app.js",
        "sourceMap": true
    },
    "files": [
        "src/app.ts"
    ]
}

直接运行tsc,会自动把src/app.ts编译到dist/app.jsweb

关于这个配置文件的更多选项,能够看官方文档typescript

使用模块

TypeScript中,模块的使用方法与ES6一致。npm

src/modules/utilities.tsjson

function getUrlParam(key: string) {

  const REG_PATTERN = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
  let result: string[] = location.search.substr(1).match(REG_PATTERN);

  if (result !== null) {
    return decodeURIComponent(result[2]);
  } else {
    return null;
  }

}

export { getUrlParam }

src/app.ts

import { getUrlParam } from './modules/utilities';

let deviceType: string = getUrlParam('deviceType');

console.log(deviceType);

编译后的app.js(TypeScript编译器在输出单个文件时,只能使用AMD或System模块规范):

define("modules/utilities", ["require", "exports"], function (require, exports) {
    "use strict";
    function getUrlParam(key) {
        var REG_PATTERN = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
        var result = location.search.substr(1).match(REG_PATTERN);
        if (result !== null) {
            return decodeURIComponent(result[2]);
        }
        else {
            return null;
        }
    }
    exports.getUrlParam = getUrlParam;
});
define("app", ["require", "exports", "modules/utilities"], function (require, exports, utilities_1) {
    "use strict";
    var deviceType = utilities_1.getUrlParam('deviceType');
    console.log(deviceType);
});

使用NPM库

咱们开发JS程序的时候,要用到NPM上的第三方的库,好比jQuery、Lodash等,可是绝大多数库都是用JS写的,没有类型提示,咱们也不能在在代码中将这些库做为模块引入。

好比咱们须要在项目中使用Lodash:

npm i --save lodash

而后在代码中引入:

import * as _ from 'lodash';

console.log(_.camelCase('helloworld'))

运行 tsc 则报错:

src/app.ts(1,20): error TS2307: Cannot find module 'lodash'.

若是想在TypeScript代码中直接使用npm上的JS库,须要借助Typings这个工具。

Typings也是一个包管理器,它管理的是JS代码“定义文件”,用Typings安装相应的定义文件后,编辑器和编译器就能够去node_modules目录中找到相应的JS库,并编译到最终的JS代码中。

先安装Typings工具:

npm i -g typings

而后安装Lodash的定义文件:

typings install --save lodash

Typings会去NPM、Bower上寻找库的做者加的定义文件,可是有的库如jQuery并无官方的定义文件,则须要从社区维护的DefinitelyTyped目录下安装:

typings install --save --ambient jquery

而后再tsconfig.json中的files配置中加入一条:

"files": [
    "src/app.ts",
    "typings/main.d.ts"
]

此时编译就不会提示找不到模块了。

安装好定义文件以后,若是使用Visual Studio Code等对TypeScript支持较好的编辑器,则会提供更增强大的代码提示功能。

使用Webpack构建

TypeScript编译器支持不少模块组织规范,如ES六、commonJS、AMD等,可是若是想要将多个ts文件打包成一个文件,TypeScript只支持AMD和System,对于浏览器应用来讲,还须要引入第三方的模块加载器。若是使用Webpack配合TypeScript的loader,则能够方便地构建浏览器能够运行的JS代码。

首先安装Webpack和ts-loader:

npm i webpack -g

npm i ts-loader --save-dev

而后配置项目目录中的webpack.config.js:

module.exports = {

  entry: './src/app.ts',
  
  output: {
    filename: 'app.js',
    path: './dist'
  },
  
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.js']
  },
  
  module: {
    loaders: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  }
  
}

而后就能够经过运行webpack来构建了,构建生成的代码自带了webpack的模块加载器,能够直接在浏览器中运行。

相关文章
相关标签/搜索