整体来看,TypeScript项目构建主要分两步:javascript
ts
项目总体转换为js
项目js
项目进行打包构建构建过程当中,对ts
文件的转换再也不使用命令行方式,因此tsc
的配置参数,须要经过tsconfig.json
文件设置。java
tsconfig.json
tsc --init
复制代码
以后,咱们会在项目目录中获得一个完整冗长的 tsconfig.json
配置文件。这个文件暂且没必要改动。node
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, ...
}
}
复制代码
webpack
构建webpack
npm i -g webpack webpack-cli
复制代码
ts-loader
和 typescript
npm i -D ts-loader typescript
复制代码
webpack.config.js
const path = require('path')
module.exports = {
mode: 'production',
entry: {
main: './index.ts'
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
output: {
filename: 'webpack-bundle.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs',
},
resolve: {
extensions: ['.ts']
}
}
复制代码
webpack
通过上述配置以后,在控制台项目路径内,中直接运行 webpack
。webpack
% webpack
Hash: 1c028195d238a71fe1c7
Version: webpack 4.41.3
Time: 726ms
Built at: 2019/12/17 下午2:56:12
Asset Size Chunks Chunk Names
index.js 1.61 KiB 0 [emitted] main
Entrypoint main = index.js
[0] ./a.ts 147 bytes {0} [built]
[1] ./b.ts 147 bytes {0} [built]
[2] ./index.ts 318 bytes {0} [built]
[3] ./c.ts 378 bytes {0} [built]
复制代码
在 dist
中,生成了一个转换且合并完成的 webpack-bundle.js
文件。web
gule
构建gule
npm i -g gulp
复制代码
gulp
browserify
tsify
vinyl-source-stream
npm i -D gulp browserify tsify vinyl-source-stream
复制代码
gulpfile.js
文件const gulp = require('gulp')
const tsify = require('tsify')
const browserify = require('browserify')
const source = require('vinyl-source-stream')
gulp.task('default', () => {
return browserify({
basedir: '.',
debug: true,
entries: ['index.ts'],
cache: {},
packageCache: {}
}).plugin(tsify).bundle()
.pipe(source('gulp-bundle.js'))
.pipe(gulp.dest('dist'))
})
复制代码
gulp
通过上述配置以后,在控制台项目路径内,中直接运行 gulp
。typescript
% gulp
[15:37:30] Using gulpfile ~/ts-learn/bundle/gulpfile.js
[15:37:30] Starting 'default'...
[15:37:32] Finished 'default' after 1.4 s
复制代码
在 dist
中,生成了一个转换且合并完成的 gulp-bundle.js
文件。npm
npm
指令咱们将这两个指令整合到项目指令中:json
"scripts": {
"test": "ts-node test",
"build-webpack": "webpack",
"build-gulp": "gulp",
"build": "npm run build-webpack"
}
复制代码
这里分别针对 webpack
/ gulp
添加了构建指令,并将 build
指令设置为默认使用 webpack
构建。gulp
就酱ui