const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const tsImportPluginFactory = require('ts-import-plugin');
const webpack = require('webpack');
const htmlChunks = ['app'];
const packageJson = require('../package.json');
const path = require('path');
const paths = require('./paths')
const BASENAME = process.env.BASENAME || '';

module.exports = {
  output: {
    path: paths.build,
    filename: '[name].bundle.js',
    publicPath: paths.publicPath,
    filename: 'js/[name].[contenthash].js',
    chunkFilename: 'js/[name].[chunkhash:5].js',
    pathinfo: false,
    clean: true, // 在生成文件之前清空 output 目录
  },
  cache: {
    // 将缓存类型设置为文件系统
    type: 'filesystem',
    buildDependencies: {
      // 推荐在 webpack 配置中设置 cache.buildDependencies.config: [__filename] 来获取最新配置以及所有依赖项
      config: [__filename]
    }
  },
  // Customize the webpack build process
  plugins: [
    new CleanWebpackPlugin(),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
      VERSION: JSON.stringify(packageJson.version),
      BASENAME: JSON.stringify(BASENAME),
    }),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      meta: {
        version: packageJson.version,
      },
      inject: 'body',
      base: BASENAME,
      chunks: htmlChunks,
      showErrors: false,
      chunksSortMode: function (chunk1, chunk2) {
        var order1 = htmlChunks.indexOf(chunk1.names[0]);
        var order2 = htmlChunks.indexOf(chunk2.names[0]);
        return order1 - order2;
      },
    }),
    new webpack.ProvidePlugin({
      THREE: 'three',
    }),
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/,
    }),
  ],

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules|modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              getCustomTransformers: () => ({
                before: [
                  tsImportPluginFactory({
                    libraryName: '@easyv/antd',
                    libraryDirectory: 'lib',
                    style: true,
                  }),
                ],
              }),
              compilerOptions: {
                module: 'es2015',
              },
            },
          }
        ],
      },

      { test: /\.(js|jsx)$/, include: path.resolve(__dirname, '../src/scripts'), use: ['thread-loader', 'babel-loader?cacheDirectory=true'], },

      {
        test: /\.(?:ico|gif|png|jpg|jpeg|webm|woff(2)?|eot|ttf|otf|svg)$/i, type: 'asset', 
        parser:{
          dataUrlCondition: { // 小于1k 就转换成base64
            maxSize: 1 * 1024,
          }
        },
        generator: {
          filename: 'assets/[name][ext]',
        },
      },
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          'thread-loader',
          'source-map-loader'
        ]
      },
    ],
  },

  resolve: {
    // 针对npm中的第三方库模块，优先采用jsnext:main中指向ES6模块化语法的文件
    mainFields: ['jsnext:main', 'browser', 'main'],
    extensions: ['.ts', '.tsx', '.js', '.jsx', 'less'],
    alias: {
      react: path.resolve(__dirname, '../node_modules/react'),
      csv: path.resolve(__dirname, '../node_modules/csv'),
      // 'react-draggable': path.resolve(__dirname, '../src/scripts/components/Draggable/react-draggable.js'),
      modules: path.resolve(__dirname, '../modules'),
      images: path.resolve(__dirname, '../src/images'),
      utils: path.resolve(__dirname, '../src/scripts/utils'),
      constants: path.resolve(__dirname, '../src/scripts/constants'),
      components: path.resolve(__dirname, '../src/scripts/components'),
      containers: path.resolve(__dirname, '../src/scripts/containers'),
      models: path.resolve(__dirname, '../src/scripts/models'),
      services: path.resolve(__dirname, '../src/scripts/services'),
      hooks: path.resolve(__dirname, '../src/scripts/hooks'),
      '@': path.resolve(__dirname, '../src/scripts'),
    },
    fallback: {
      path: require.resolve("path-browserify"),
      "stream": require.resolve("stream-browserify"),
      "buffer": require.resolve("buffer"),
      "events": require.resolve("events")
    },
    symlinks: false,
    cacheWithContext: false
  },
}
