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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM