npm init
新建如下文件目錄:html
"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" }
{ "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.htmlnode
{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "corejs": "2" } ] ] }
useBuiltIns:"usage" 將會按需引入babel/polyfill。webpack
babel7已經廢棄了@babel/preset-stage-0等preset。es6
具體參考https://www.babeljs.cn/docs/babel-preset-envweb
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並加入polyfilltypescript
參數含義參考https://webpack.docschina.org/configuration/npm
"scripts": { "compile": "webpack" },
好比咱們在src下定義index.tsjson
const testFunc = (num: number) => { const arr: number[] = [1, 2, 3, 4]; return arr.includes(num); }; export { testFunc };
其中使用了箭頭函數和ES7方法includes。babel
執行打包:函數
打包完成,此時在dist下已經打包出了ma.min.js文件,其中includes方法也被作了polyfill處理。
ts-loader也能夠直接打包成es5語法,但不會作polyfill,何況若是項目依賴babel生態中的其餘插件,也須要使用babel-loader.