webpack + typescript + babel打包*.min.js文件的环境配置
将多个*.ts文件打包成一个*.min.js文件的开发配置
1、初始化
npm init
新建以下文件目录:
2、安装依赖:
"devDependencies": { "@babel/core": "^7.4.5", "@babel/preset-env": "^7.4.5", "babel-loader": "^8.0.6", "ts-loader": "^6.0.3", "typescript": "^3.5.2", "webpack": "^4.35.0", "webpack-cli": "^3.3.4" }, "dependencies": { "@babel/polyfill": "^7.4.4", "core-js": "2" }
3、tsconfig.json
{ "compileOnSave": false, "compilerOptions": { "sourceMap": true, "noImplicitAny": false, "noUnusedParameters": true, "moduleResolution": "node", "module": "esnext", "target": "esnext", "baseUrl": "./" }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }
参数含义参考https://www.tslang.cn/docs/handbook/compiler-options.html
4、babelrc
{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "corejs": "2" } ] ] }
useBuiltIns:”usage” 将会按需引入babel/polyfill。
babel7已经废弃了@babel/preset-stage-0等preset。
具体参考https://www.babeljs.cn/docs/babel-preset-env
5、webpack.config.js
const path = require("path"); module.exports = { mode: "production", entry: "./src", output: { path: path.resolve(__dirname, "dist"), filename: "ma.min.js", library: "MA", libraryTarget: "umd" }, module: { rules: [ { test: /\.ts$/, use: ["babel-loader", "ts-loader"], exclude: [path.resolve(__dirname, "node_modules")] } ] }, resolve: { extensions: [".ts", ".js"] } // devtool: "inline-source-map" };
ts文件将会经过ts-loader转成es6,再由babel-loader转成es5并加入polyfill
参数含义参考https://webpack.docschina.org/configuration/
6、package.json中定义script
"scripts": { "compile": "webpack" },
7、执行打包
比如我们在src下定义index.ts
const testFunc = (num: number) => { const arr: number[] = [1, 2, 3, 4]; return arr.includes(num); }; export { testFunc };
其中使用了箭头函数和ES7方法includes。
执行打包:
打包完成,此时在dist下已经打包出了ma.min.js文件,其中includes方法也被做了polyfill处理。
8、为什么使用了ts-loader后还要使用babel-loader
ts-loader也可以直接打包成es5语法,但不会做polyfill,况且如果项目依赖babel生态中的其他插件,也需要使用babel-loader.