/**
 * 开发环境 webpack 配置
 *
 * @author : Sunkey
 */

const path = require('path')
const _ = require('lodash')
const webpack = require('webpack')
const autoprefixer = require('autoprefixer')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const modules = require('./modules')

// 文件的发布目录（打包文件将生成到这个目录）
const releasePath = path.join(__dirname, '../build/')

// 脚本加载目录（script 加载文件的目录前缀）
const publicPath = '/build/'

// webpack 配置
let webpackConfig = {
    entry: {
        vendors: [
            'antd',
            'lodash',
            'moment',
            'react',
            'react-dom',
            'react-redux',
            'redux',
            'redux-thunk',
            'isomorphic-fetch',
        ],
    },

    output: {
        path: releasePath,
        filename: '[name].[hash].min.js', // 脚本名
        publicPath: publicPath,
    },

    module: {
        loaders: [
            {
                test: /\.(css)$/,
                loader: ExtractTextWebpackPlugin.extract(['css', 'postcss']),
            },
            {
                test: /\.(less)$/,
                loader: ExtractTextWebpackPlugin.extract(['css', 'postcss', 'less']),
            },
            {
                test: /\.(scss)$/,
                loader: ExtractTextWebpackPlugin.extract(['css', 'postcss', 'sass']),
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loaders: ['react-hot', 'babel?presets[]=react&presets[]=es2015'],
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
                loaders: ['url?limit=8192&name=./styles/static/[name].[ext]'],
            },
        ],
    },

    postcss: [autoprefixer],

    plugins: [
        new ProgressBarPlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.NoErrorsPlugin(), 
        new ExtractTextWebpackPlugin('./styles/bundle.css'),
        new webpack.optimize.CommonsChunkPlugin('vendors', '[name].[hash].min.js'),
        new webpack.optimize.UglifyJsPlugin({mangle: false, sourceMap: false}),
    ],
}

/**
 * 注入模块打包配置
 * @param  {Object} webpackConfig webpack主配置
 * @return {null}
 */
function injectModuleConfig(webpackConfig) {
    _.forOwn(_.omitBy(modules, (moduleConfig, module) => {
        return !moduleConfig.build
    }), (moduleConfig, module) => {
        webpackConfig.entry[module] = moduleConfig.entryJs
        webpackConfig.plugins.push(
            new HtmlWebpackPlugin({
                template: moduleConfig.templatePath,
                inject: 'body',
                chunks: ['vendors', module],
            })
        )
    })
}

injectModuleConfig(webpackConfig)

module.exports = webpackConfig
