const fs = require('fs');
const path = require('path');
const StringReplacePlugin = require("string-replace-webpack-plugin");

function resolveThreeModule() {
    // const threePath = require.resolve(path.resolve(process.cwd(), 'node_modules', 'three'))
    const cwd = process.env.CWD || process.cwd();
    const threePath = require.resolve(path.resolve(cwd, 'node_modules', 'three'));

    const code = fs.readFileSync(path.resolve(threePath), 'utf8');
    return code;
}

// es5 babel 配置
const _babelConfig = {
    loader: 'babel-loader',
    options: {
        presets: [[
            "@babel/preset-env",
            {
                "modules": false,
                "targets": {
                    "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
                }
            }
        ]
        ],
        plugins: [
            ["@babel/plugin-proposal-class-properties", {"loose": true}]
        ]
    }
};

module.exports = {
    mode: "production",
    entry: path.join(__dirname, '../src/index'),
    target: 'web',
    output: {
        path: path.join(__dirname, '../dist'),
        filename: 'index.js',
        libraryTarget: 'commonjs',
    },
    module: {
        rules: [
            {
                test: /\/index.js$/,
                use: [
                    _babelConfig,
                    {
                        loader: StringReplacePlugin.replace({
                            replacements: [
                                {
                                    // eslint-disable-next-line no-useless-escape
                                    pattern: /\'__INJECT_THREE__\'/ig,
                                    replacement: () => {
                                        return resolveThreeModule();
                                    }
                                }
                            ]
                        })
                    },
                ]
            }, {
                test: /.js$/,
                use: [ _babelConfig ]
            }
        ]
    },
    plugins: [
        // an instance of the plugin must be present
        new StringReplacePlugin()
    ],
    optimization:{
        minimize: true,
    }
}
