webpack.config.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const path = require('path');
  2. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  3. const TerserPlugin = require('terser-webpack-plugin');
  4. module.exports = {
  5. entry: './src/index.js', // 你的源码入口(确保指向正确的 index.js)
  6. target: ['web', 'es5'],
  7. mode: 'production',
  8. output: {
  9. path: path.resolve(__dirname, 'dist'),
  10. filename: 'main.js',
  11. // 关键:设置 UMD 导出,暴露变量名为 UtmTracker
  12. library: 'UtmTracker', // 全局变量名(浏览器环境)
  13. libraryTarget: 'umd', // 支持 UMD 格式
  14. globalObject: 'this', // 兼容浏览器(window)和 Node(global)
  15. umdNamedDefine: true // 为 AMD 模块命名,避免匿名问题
  16. },
  17. plugins: [
  18. new CleanWebpackPlugin() // 打包前清理 dist 目录
  19. ],
  20. optimization: {
  21. minimizer: [
  22. new TerserPlugin({
  23. terserOptions: {
  24. // 禁止压缩时混淆 UtmTracker 名称
  25. keep_fnames: /UtmTracker/, // 保留构造函数名
  26. keep_classnames: true // 若用 class 定义,保留类名
  27. }
  28. })
  29. ]
  30. },
  31. module: {
  32. rules: [
  33. {
  34. test: /\.js$/,
  35. exclude: /node_modules/,
  36. use: 'babel-loader' // 确保 ES6+ 语法被转译
  37. }
  38. ]
  39. }
  40. };