/*
 * @Description: webpack 配置文件
 * @Author: realrain☔ 1936648485@qq.com
 * @Date: 2025-10-19 16:04:58
 * @LastEditors: realrain☔ 1936648485@qq.com
 * @LastEditTime: 2025-11-19 17:14:45
 * @FilePath: \findme-miniprogram\webpack.config.js
 * @X/Facebook: 1936648485@qq.com ~~~~~~~~~~~~~~~~~~~~~~~ Blog：reallyrain.com
 * Copyright (c) 2025 by real-rain, All Rights Reserved. 
 */
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path')
const fs = require('fs')

/**
 * 清空 dist 文件夹
 */
if (fs.existsSync(path.resolve(__dirname, 'dist'))) {
  fs.rmSync(path.resolve(__dirname, 'dist'), { recursive: true, force: true })
}

/**
 * 自定义插件：在构建完成后复制文件
 */
class CopyFilesPlugin {
  apply(compiler) {
    compiler.hooks.done.tap('CopyFilesPlugin', () => {
      // 复制 COS SDK 的 min.js 文件
      const cosSource = path.resolve(__dirname, 'node_modules', 'cos-wx-sdk-v5', 'dist', 'cos-wx-sdk-v5.min.js')
      const cosTarget = path.resolve(__dirname, 'dist', 'cos-wx-sdk-v5.min.js')
      if (fs.existsSync(cosSource)) {
        fs.copyFileSync(cosSource, cosTarget)
        console.log('[CopyFiles] COS SDK 已复制')
      }

      // 复制 SparkMD5 的 min.js 文件
      const sparkSource = path.resolve(__dirname, 'node_modules', 'spark-md5', 'spark-md5.min.js')
      const sparkTarget = path.resolve(__dirname, 'dist', 'spark-md5.min.js')
      if (fs.existsSync(sparkSource)) {
        fs.copyFileSync(sparkSource, sparkTarget)
        console.log('[CopyFiles] SparkMD5 已复制')
      }
    })
  }
}

module.exports = {
  experiments: {
    outputModule: true
  },
  entry: {
    app: path.resolve(__dirname, 'utils', 'nim.js')
  },
  output: {
    filename: 'nim.js',
    libraryTarget: 'module',
    path: path.resolve(__dirname, 'dist'),
    // 每次构建新产物前, 能删除旧产物
    clean: true
  },
  mode: 'production',
  devtool: false,
  optimization: {
    usedExports: true
  },
  plugins: [
    new CopyFilesPlugin()
  ]
}
