const webpack = require('webpack')
const path = require('path');
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
const Timestamp = new Date().getTime()

const createServerConfig = function (compilation) {
    let config = { version: new Date().getTime() }
    return JSON.stringify(config)
}

function resolve(dir) {
    return path.join(__dirname, dir)//设置绝对路径
}

module.exports = {
    devServer: {
        port: "8080", //代理端口
        open: false, //项目启动时是否自动打开浏览器，我这里设置为false,不打开，true表示打开
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
        proxy: {
            '/cloudApi': {
                target: 'http://120.79.80.64:8050',
                ws: true,
                pathRewrite: {
                    '^/api': '/'
                }
            },
        }
    },
    chainWebpack: (config) => {
        config.resolve.alias
            .set('_static', resolve('src/assets'))//参数1,设置的别名,参数2：设置的路径
        config
            .plugin('html')
            .tap(args => {
                args[0].title = '智能仓储一体机'
                return args
            })
    },
    // 设为false打包时不生成.map文件
    productionSourceMap: false,
    configureWebpack: config => {
        // 开发环境不需要gzip 生产环境时清空所有console
        if (process.env.NODE_ENV !== 'production') return
        else config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
        config.plugins.push(
            new CompressionWebpackPlugin({
                // 正在匹配需要压缩的文件后缀
                test: /\.(js|css|svg|woff|ttf|json|html)$/,
                // 大于10kb的会压缩
                threshold: 10240
                // 其余配置查看compression-webpack-plugin
            })
        )
        config.plugins.push(
            new GenerateAssetPlugin({
                filename: 'version.json',
                fn: (compilation, cb) => {
                    cb(null, createServerConfig(compilation))
                },
                extraFiles: []
            })
        )
        config.plugins.push(
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery'
            })
        )
        config.output.filename = `js/[name].${Timestamp}.js`
        config.output.chunkFilename = `js/[name].${Timestamp}.js`
    }
}
