TypeScript + Webpack 环境搭建步骤
- 安装Node.js
- 安装npm
- 创建一个npm项目
- 安装typescript,配置ts
- 安装webpack,配置webpack
初始化一个npm项目
npm init
将在项目根目录下创建package.json
文件。文件目录结构如下
ts3-demo|- src ?|- index.ts|- package.json
全局安装typescript命令:
npm install -g typescript
可以使用以下命令来查看你的机器中是否安装了Node.js npm typescript,以及安装的版本。
node -vnpm -vtsc -v
typescript compiler
typescript的编译器叫做 tsc。
假设有个src/index.ts 文件,将它编译成index.js,可以使用命令:
tsc src/index.ts --target es5 或者tsc src/index.ts --target es3
启动观察模式,当ts文件更改之后,自动进行编译。
tsc src/index.ts --watch --target es5
// index.tsexport default class Index { ???title = ‘Hello‘; ???name = ‘Lori‘; ???}
编译后结果
"use strict";Object.defineProperty(exports, "__esModule", { value: true });var Index = /** @class */ (function () { ???function Index() { ???????this.title = ‘Hello‘; ???????this.name = ‘Lori‘; ???} ???return Index;}());exports.default = Index;
通常不会在terminal中敲命令来编译,而是在项目的根路径下,建一个json配置文件 tsconfig.json
,来配置这些编译选项。
初始化tsconfig.json
的命令:
tsc --init
然后在terminal中使用tsc命令,会发现项目中所有ts文件都被编译成了js文件。
tsc
配置tsconfig.json
{ ?"compileOnSave": false, ?"compilerOptions": { ???"outDir": "./dist/out-tsc", ???"sourceMap": true, ???"declaration": false, ???"moduleResolution": "node", ???"emitDecoratorMetadata": true, ???"experimentalDecorators": true, ???"target": "es5", ???"typeRoots": [ ?????"node_modules/@types" ???], ???"lib": [ ?????"es2017", ?????"dom" ???] ?}}
安装Webpack
npm install webpack webpack-cli --save-dev
安装ts-loader
npm install ts-loader --save-dev
安装Webpack插件 html-webpack-plugin
用于自动生成index.html文件。
npm install html-webpack-plugin --save-dev
配置webpack.config.ts
const path = require(‘path‘);const HtmlWebpackPlugin = require(‘html-webpack-plugin‘);module.exports = { ???mode: "development", ???devtool: "inline-source-map", ????entry: "./src/index.ts", ???output: { ???????path: __dirname + ‘/dist‘, ???????filename: ‘[name].bundle.js‘ ???}, ???resolve: { ???????extensions: [‘.ts‘, ‘.tsx‘, ‘.js‘] ???}, ???plugins: [ ???????new HtmlWebpackPlugin({ ???????????title: ‘index‘ ???????}) ???], ???module: { ???????rules: [ ???????????{ ???????????????test: /\.tsx?$/, ???????????????use: ‘ts-loader‘, ???????????????exclude: /node_modules/ ???????????} ???????] ???}, ???devServer: { ???????contentBase: path.join(__dirname, ‘dist‘), ????????compress: true, ????????historyApiFallback: true, ????????hot: true, ???}}
想要在debug时生成相应的map文件,注意两点:
tsconfig.json
中 sourceMap 设置为 truewebpack.config.ts
中 devtool: "inline-source-map"
配置package.json
添加命令
"scripts": { ???"start": "./node_modules/.bin/webpack-dev-server", ???"build": "./node_modules/.bin/webpack", ???"test": "echo \"Error: no test specified\" && exit 1" ?},
运行npm run build
进行编译。
文件目录结构如下
ts3-demo|-dist ?|- index.html ?|- main.bundle.js|- src ?|- index.ts|- package.json|- tsconfig.json|- webpack.config.js
运行npm start
启动本地服务器。
TypeScript + Webpack 环境搭建
原文地址:https://www.cnblogs.com/liulei-cherry/p/9687201.html