webpack + typescript + babel打包*.min.js文件的环境配置

将多个*.ts文件打包成一个*.min.js文件的开发配置

 

一、初始化

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"
  }

 

三、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.htmlnode

 

四、babelrc

{
  "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

 

五、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并加入polyfilltypescript

参数含义参考https://webpack.docschina.org/configuration/npm

 

六、package.json中定义script

"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后还要使用babel-loader

ts-loader也能够直接打包成es5语法,但不会作polyfill,何况若是项目依赖babel生态中的其余插件,也须要使用babel-loader.

相关文章
相关标签/搜索