/**
 * 144915 type-vue插件支持双进程模式编译
 * @type {webpack}
 */

let webpack = require('webpack');

const config = require("./webpack.config");
const merge = require("webpack-merge");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const distCss = new ExtractTextPlugin({
    filename:"[name].miniapp.css", allChunks: true,disable: false,
})

let webpackconfig = {
    output: {
        path: light.config.dist,
        //75948 异步视图支持添加反缓存的后缀
        chunkFilename: 'lightdist/[name].miniapp.js?[chunkhash]',
        filename: '[name].miniapp.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    compilerModules: require("./lib/utils").hasPlugin('jsnative') ? [{
                        postTransformNode: el => {
                            require('weex-vue-precompiler')()(el)
                        }
                    }] : undefined,
                    loaders: {
                        css: distCss.extract({
                            use: 'css-loader',
                            fallback: 'vue-style-loader'
                        }),
                        less: distCss.extract({
                            use: 'css-loader!less-loader?indentedSyntax',
                            fallback: 'vue-style-loader'
                        }),
                    },
                    extractCSS: true,
                    postcss:[
                        require('autoprefixer')({
                            browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12']
                        }),
                        require('postcss-plugin-px2rem')({
                            rootValue: 75,
                            minPixelValue: 1.01
                        })
                    ]
                }
            }
        ],
    },
    plugins: [
        distCss,
        new webpack.DefinePlugin({
            'process.env.RUNTIME': JSON.stringify("miniapp"),
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            '__ENV__': require("./env")(light.options.env || 'default')
        }),
    ],
    externals: {
        vue: 'Vue'
    },
    resolve:{
        // jsnative的支持已经移除，此文件无需存在 
        // alias:{
        //     "miniapp-vue-render4light":require("path").join(light.config.pluginsDir,"node_modules/lighting-plugin-miniapp/render")
        // }
    }
};
if (light.options.watch) {
    webpackconfig = merge({
        watch: true,
        watchOptions: {
            ////105231 多页工程的每个.native.js文件都不监听变化
            ignored: (function () {
                return ['app.miniapp.js'];
            })()
        }
    }, webpackconfig)
}

//201467【小程序】light release --console 时设置__base__DEBUG_MODE=true 到代码中
function extend(item) {
    let entryObj = { entry: {} };
    for (var key in config.entry) {
        entryObj.entry[key] = item;
    }
    return entryObj;
}
if (light.options.console) {
    webpackconfig = merge(extend([`${__dirname}/plugins/vconsole.js`]), webpackconfig)
}

module.exports = {
    build() {
        let distConfig = merge(webpackconfig, config);

        // 154005 【Light小程序】【工程转译】支持JSNative工程转译直接编译为小程序目标-scroller 、list等可滚动标签处理
        // if(require("./lib/utils").hasPlugin('jsnative')) {
        //     Object.keys(distConfig.entry).forEach(function (key) {
        //         distConfig.entry[key] = [`${__dirname}/miniapp.init.js`].concat(distConfig.entry[key]);
        //     });
        // }

        distConfig.module.rules.forEach(function (rule) {
            if(rule.test.test("rule.less")){ // 说明：rule.less只是为了检验此规则的存在，并不需要存在此文件
                rule.use  = distCss.extract({
                    fallback: "style-loader",
                    use: ['css-loader', 'less-loader']
                })
            }
        });

        // 59972 【lighting】可以考虑在现有约定的基础上开放自定义配置接口（Webpack和Babel）
        let buildJS = require("path").join(light.config.src, "build.js");
        if (require("fs").existsSync(buildJS)) {
            distConfig = require(buildJS).build(distConfig, merge, webpack)
        }

        return distConfig;
    }
};
