const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
    chainWebpack: (config) => {
        // 移除 prefetch 插件
        config.plugins.delete('prefetch');
    },
    assetsDir: 'assets',
    productionSourceMap: !isProduction,

    // 暂时没有找到publicPath的单独配置,无法解决CDN的问题
    css: {
        sourceMap: true,
    },

    // lintOnSave: 'error',
    lintOnSave: false,
    // 避免静态资源请求时附带Cookie,最终目的是减少资源请求包的大小
    crossorigin: 'anonymous',
    // 保证资源的安全性,避免劫持后的安全问题
    integrity: true,

    devServer: {
        // 启动且第一次构建完成时,自动用我们的系统的默认浏览器去打开要开发的网页
        open: true,
        disableHostCheck: true,
        proxy: {
            '/phpapi': {
                target: process.env.VUE_APP_PHP_URL,
                changeOrigin: true,
                pathRewrite: { '^/phpapi': '' },
                // 另外的细节
                // 浏览器对Port的处理存在差异,这是同源策略中的灰色地带,即:80端口的Cookie在Chrome等其他浏览器中会发送到:8080,而Firefox不会)。
                // cookieDomainRewrite: '',
                // secure: false,
            },
        },
    },

    configureWebpack: {
        module: {
            rules: [
                {
                    test: /\.s[ac]ss$/i,
                    use: [
                        // Compiles Sass to CSS
                        'sass-loader',
                    ],
                },
                {
                    test: /\.js$/,
                    loader: ['babel-loader', 'eslint-loader'],
                    exclude: file => (/node_modules/.test(file)),
                },
            ],
        },
        plugins: [
            new CopyPlugin([
                { from: path.resolve(__dirname, '.htaccess'), to: path.resolve(__dirname, 'dist') },
            ]),
        ],
        resolve: {
            mainFields: ['browser', 'module', 'main'],
            alias: {
                '@': path.resolve(__dirname, 'src'),
            },
        },
        optimization: {
            minimizer: [
                new UglifyJsPlugin({
                    uglifyOptions: {
                        warnings: false,
                        compress: {
                            drop_console: true, // console
                            drop_debugger: true,
                            pure_funcs: ['console.log'], // 移除console
                        },
                        output: {
                            beautify: false, // 最紧凑的输出,不保留空格和制表符
                            comments: false, // 删除所有注释
                        },
                    },
                    sourceMap: false,
                    parallel: true,
                }),
            ],
        },
    },
};