webpack 打包ts项目_webpack打包纯ts项目

场景

当我们单纯用ts开发一个公有库时,没有了脚手架的帮助,我们需要借助webpack完成该ts项目的打包。

核心要点:

将ts编译成js

对打包进行自定义配置

依赖包

webapck(打包工具,必须)

ts-loader(将ts编译成js的loader,必须)

ts-lint(检测ts代码是否规范,非必须)

clean-webpack-plugin(每次打包时,删除上次打包的残留文件,保证打出的包整洁,非必须)

tsconfig.json配置

{

"compileOnSave": false,

"compilerOptions": {

"outDir": "./dist/",// 打包到的目录

"sourceMap": true,// 是否生成sourceMap(用于浏览器调试)

"noImplicitAny": false,

"noUnusedLocals": true,

"noUnusedParameters": true,

"declaration": true,// 是否生成声明文件

"declarationDir": "./dist/types/",// 声明文件打包的位置

"declarationMap": true,// 是否生成声明文件map文件(便于调试)

"moduleResolution": "node",

"module": "esnext",

"target": "es5",// 转化成的目标语言

"baseUrl": "./",

"types": [

"node",

"jest"

],

"typeRoots": [

"./node_modules/@types"

],

"lib": [

"dom",

"es2015"

],

"jsx": "react",

"allowJs": false

},

"include": [

"src/**/*.ts"

],// 要打包的文件

"exclude": [

"node_modules",

"*.test.ts"

]

}

webpack.config.js

const path = require('path');

const CleanWebpackPlugin = require('clean-webpack-plugin');

// the path(s) that should be cleaned

let pathsToClean = ['dist'];

// the clean options to use

let cleanOptions = {

root: path.resolve(__dirname),

// exclude: ['shared.js'],

verbose: true,

dry: false,

};

module.exports = {

resolve: {

extensions: ['.js', '.ts', '.json'],

},

devtool: 'source-map',// 打包出的js文件是否生成map文件(方便浏览器调试)

mode: 'production',

entry: {

‘my-ts': './src/index.ts',

},

output: {

filename: '[name].js',// 生成的fiename需要与package.json中的main一致

path: path.resolve(__dirname, 'dist'),

libraryTarget: 'commonjs',

},

module: {

rules: [

{

test: /\.tsx?$/,

use: [

{

loader: 'tslint-loader',

options: {

configFile: path.resolve(__dirname, './tslint.json'),

},

},

],

exclude: /node_modules/,

},

{

test: /\.tsx?$/,

use: [

{

loader: 'ts-loader',

options: {

// 指定特定的ts编译配置,为了区分脚本的ts配置

configFile: path.resolve(__dirname, './tsconfig.json'),

},

},

],

exclude: /node_modules/,

},

],

},

plugins: [new CleanWebpackPlugin(pathsToClean, cleanOptions)],

};

package.json

{

"name": "my-ts-project",

"version": "1.0.0",

"description": "",

"main": "./dist/my-ts.js",// 需要与webpack打包出来的内容一致

"types": "./dist/types/index.d.ts",// 需要与types文件的路径一致

"private": false,

"publisher": "[email protected]",

"scripts": {

"build": "tsc",

"test": "jest"

},

"files": [

"dist"

],// 最终发布到npm上时提交的内容

"repository": {

"type": "",

"url": ""

},

"keywords": [

"my-ts"

],

"author": "[email protected]",

"license": "MIT",

"devDependencies": {

"@types/jest": "^23.3.1",

"@types/node": "^10.5.5",

"clean-webpack-plugin": "^1.0.1",

"jest": "^23.4.2",

"prettier": "^1.16.4",// 优化代码格式

"ts-jest": "^23.0.1",

"ts-lint": "^4.5.1",

"ts-loader": "^5.3.3",

"tslint": "^5.11.0",

"tslint-loader": "^3.5.4",

"typescript": "^3.0.1",

"webpack": "^4.28.1"

}

}

你可能感兴趣的:(webpack,打包ts项目)