下载依赖:

typescript

ts-loader
webpack
webpack-cli

html-webpack-plugin
clean-webpack-plugin

@babel/core babel核心库
@babel/preset-env //babel预定义环境(兼容各种浏览器)
babel-loader
core-js //模拟js

创建webpack.config.js

  1. const path = require('path');
  2. //引入html插件
  3. const HtmlWebpackPlugin = require('html-webpack-plugin')
  4. //引入clean插件
  5. const {CleanWebpackPlugin} = require('clean-webpack-plugin')
  6. module.exports = {
  7. //入口文件
  8. entry: './src/index.ts',
  9. //模式
  10. mode:'development',
  11. context: path.resolve(__dirname),
  12. //指定打包文件所在目录
  13. output: {
  14. //指定打包文件的目录
  15. path: path.resolve(__dirname, 'dist'),
  16. //打包后的文件名
  17. filename: 'bundle.js',
  18. //告诉webpack 不使用箭头函数
  19. environment:{
  20. arrowFunction:false
  21. }
  22. },
  23. //指定webpage打包是要使用的模块
  24. module: {
  25. //指定要加载的规则
  26. rules: [
  27. {
  28. //test指定规则生效的文件
  29. test:/\.ts$/,
  30. //要使用的loader,use的执行顺序是 从下往上
  31. use:[
  32. {
  33. //指定加载器
  34. loader:'babel-loader',
  35. //设置babel
  36. options:{
  37. //设定预定义环境
  38. presets:[
  39. [
  40. //指定环境的插件
  41. '@babel/preset-env',
  42. //配置信息
  43. {
  44. //要兼容的目标浏览器
  45. targets:{
  46. "chrome":"88",
  47. "ie":'8'
  48. },
  49. //指定corejs的版本 处理类似Promise这种特殊的类
  50. "corejs":"3",
  51. //使用corejs的方式“usage”表示按需加载
  52. "useBuiltIns":"usage"
  53. }
  54. ]
  55. ]
  56. }
  57. },
  58. 'ts-loader'
  59. ],
  60. //要排除的文件
  61. exclude:/node_modules/
  62. }
  63. ]
  64. },
  65. //后缀
  66. resolve: {
  67. extensions:['.ts,','.js']
  68. },
  69. // devtool: 'source-map',
  70. //配置webapck插件
  71. plugins: [
  72. new HtmlWebpackPlugin({
  73. title:'自定义title',
  74. //html模版
  75. template:"./src/index.html"
  76. }),
  77. //更新打包后文件,删除修改项
  78. new CleanWebpackPlugin()
  79. ]
  80. };

创建ts配置文件tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "module": "ES2015",
  4. "target": "ES2015",
  5. "sourceMap": false,
  6. "strict": true
  7. }
  8. }