当前位置: 移动技术网 > IT编程>开发语言>JavaScript > webpack + typescript + babel打包*.min.js文件的环境配置

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

2019年06月21日  | 移动技术网IT编程  | 我要评论

将多个*.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"]
}

参数含义参考

 

4、babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "usebuiltins": "usage",
        "corejs": "2"
      }
    ]
  ]
}

usebuiltins:"usage" 将会按需引入babel/polyfill。

babel7已经废弃了@babel/preset-stage-0等preset。

具体参考

 

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

参数含义参考

 

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.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网