'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const vueLoaderConfig = require('./vue-loader.conf')
const workerConfig = require('./worker.conf')
// const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// const ESLintPlugin = require('eslint-webpack-plugin');
// const VueLoaderPlugin = require('vue-loader/lib/plugin');
// const {VueLoaderPlugin} = require('vue-loader')
const portfinder = require('portfinder')
function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = {
  cache: {
    type: 'filesystem',
    allowCollectingMemory: true,
    buildDependencies: {
      // This makes all dependencies of this file - build dependencies
      config: [__filename],
      // 默认情况下 webpack 与 loader 是构建依赖。
    },
  },
  target: 'web',
entry: {
  app: './src/main.js',
 // sdk: path.join(__dirname, '../src/sdk/NIM_Web_SDK_v5.0.0.js')
},
externals:{
  'BMap':'BMap',
},
resolve: {
  extensions: ['.js', '.vue', '.json'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src'),
  },
  fallback: {
    timers: require.resolve("timers-browserify"),
    zlib: require.resolve("browserify-zlib"),
    "constants": require.resolve("constants-browserify"),
    "os": require.resolve("os-browserify/browser")
}
},
  mode: 'development',
  // 避免额外的优化步骤 Webpack 通过执行额外的算法任务,来优化输出结果的体积和加载性能。这些优化适用于小型代码库,但是在大型代码库中却非常耗费性能
  // optimization: {
  //   removeAvailableModules: false,
  //   removeEmptyChunks: false,
  //   splitChunks: false,
  // },
  output: { //Webpack 会在输出的 bundle 中生成路径信息。然而,在打包数千个模块的项目中,这会导致造成垃圾回收性能压力。在 options.output.pathinfo 设置中关闭
    pathinfo: false,
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  module: {
  rules: [
    // ...(config.dev.useEslint ? [createLintingRule()] : []),
    ...utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }),
    {
      test: /\.vue$/,
      use: [{loader:"thread-loader",options:workerConfig}, {loader:'vue-loader', options: vueLoaderConfig}],
      // loader:'vue-loader', options: vueLoaderConfig
    },
    {
      test: /\.js$/,
      use: [{loader:"thread-loader",options:workerConfig},'babel-loader'],
      exclude: /NIM_Web_SDK_v5.0.0.js/,
      include: [resolve('src'), resolve('test')]
    },
    {
      test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      type: "asset",
      generator: {
        filename: utils.assetsPath('img/[name].[hash:10][ext]')
      },
    },
    {
      test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
      type: "asset",
      generator: {
        filename: utils.assetsPath('media/[name].[hash:7].[ext]')
      },
    },
    {
      test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
      type: "asset",
      generator: {
        filename: utils.assetsPath('fonts/[name].[hash:7].[ext]')
      },
    },
    {
      test: /\.(mp3)(\?.*)?$/,
      type: "asset",
      generator: {
        filename: utils.assetsPath('assets/[name].[hash:7].[ext]')
      },
    }
  ]
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    allowedHosts: [HOST || config.dev.host],
    client: {
      logging: 'warn',
      reconnect: 5, //告诉 dev-server 它应该尝试重新连接客户端的次数。当为 true 时,它将无限次尝试重新连接
    },
    // clientLogLevel: 'warning',
    // historyApiFallback: {
    //   rewrites: [
    //     { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
    //   ],
    // },
    // contentBase: false, // since we use CopyWebpackPlugin.
    // compress: true,
    // host: HOST || config.dev.host,
    // port: PORT || config.dev.port,
    // open: config.dev.autoOpenBrowser,
    // overlay: config.dev.errorOverlay
    //   ? { warnings: false, errors: true }
    //   : false,
    // publicPath: config.dev.assetsPublicPath,
    // proxy: config.dev.proxyTable,
    // quiet: true, // necessary for FriendlyErrorsPlugin
    // watchOptions: {
    //   poll: config.dev.poll,
    // }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    // new ESLintPlugin(),
    // new VueLoaderPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin({patterns:[
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
      globOptions: {
        ignore: ['.*']
      },
      },
    ]})
  ]
}
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
// module.exports = new Promise((resolve, reject) => {
//   portfinder.basePort = process.env.PORT || config.dev.port
//   portfinder.getPort((err, port) => {
//     if (err) {
//       reject(err)
//     } else {
//       // publish the new Port, necessary for e2e tests
//       process.env.PORT = port
//       // add port to devServer config
//       devWebpackConfig.devServer.port = port

//       // Add FriendlyErrorsPlugin
//       // devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
//       //   compilationSuccessInfo: {
//       //     messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
//       //   },
//       //   onErrors: config.dev.notifyOnErrors
//       //   ? utils.createNotifierCallback()
//       //   : undefined
//       // }))
//       resolve(smp.wrap(devWebpackConfig))
//     }
//   })
// })
module.exports = smp.wrap(devWebpackConfig)