'use strict'
const path = require('path')
const fs = require('fs')
const utils = require('./utils')
const config = require('../config')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')
var webpack = require('webpack')
function resolve(dir) {
    return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
    test: /\.(js|vue)$/,
    loader: 'eslint-loader',
    enforce: 'pre',
    include: [resolve('src'), resolve('test')],
    options: {
        formatter: require('eslint-friendly-formatter'),
        emitWarning: !config.dev.showEslintErrorsInOverlay
    }
})

module.exports = {
    context: path.resolve(__dirname, '../'),
    entry: {
        // app: ["babel-polyfill", './src/main.js']
        // app: ['./src/main.js']
        app: './src/test/index.js'
    },
    output: {
        path: config.build.assetsRoot,
        filename: '[name].js',
        chunkFilename: '[name].js',
        publicPath: process.env.NODE_ENV === 'production' ?
            config.build.assetsPublicPath :
            config.dev.assetsPublicPath
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            '@': resolve('src'),
          'static':path.resolve(__dirname, '../static'),
        }
    },
    module: {
        rules: [
            ...(config.dev.useEslint ? [] : []),
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: vueLoaderConfig
            },
            {
                test: /\.js$/,
                loader: 'babel-loader?cacheDirectory',
                include: [
                    resolve('src'),
                    resolve('test'),
                    resolve('node_modules/webpack-dev-server/client')
                ]
            },
            {
                test: /\.svg$/,
                loader: 'svg-sprite-loader',
                include: [resolve('static/svg')],
                options: {
                    symbolId: 'icon-[name]'
                }
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                exclude: [resolve('src/icons'),resolve('static/svg')],
                options: {
                    limit: 10000,
                    // publicPath: '../../',
                    name: utils.assetsPath('img/[name].[hash:7].[ext]')
                }
            },
            {
                test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    name: utils.assetsPath('media/[name].[hash:7].[ext]')
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
                }
            }
        ]
    },
    plugins: [
      new VueLoaderPlugin(),
      function() {
        // 修改package.json中的版本号
        this.plugin('done', function() {
          if(process.env.NODE_ENV === 'production') {
            const gitHEAD = fs.readFileSync('.git/HEAD', 'utf-8').trim();
            const ref = gitHEAD.split(': ')[1];
            const commitId = ref ? fs.readFileSync('.git/' + ref, 'utf-8').trim(): gitHEAD;
            const pkgPath = path.join(__dirname, '/../package.json');
            let pkg = fs.readFileSync(pkgPath);
            pkg = JSON.parse(pkg);
            const arr =pkg.version.split('.')
            arr[2] = (arr[2]-0)+1 +''
            arr[3] = commitId.substring(0,8)
            pkg.version = arr.join('.');
            fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
          }
        });
      },
      new webpack.DefinePlugin({
        'process.env.MY_VERSION': JSON.stringify(require('../package.json').version)
        // 项目中使用 process.env.MY_VERSION 输出
      })
    ],
    node: {
        // prevent webpack from injecting useless setImmediate polyfill because Vue
        // source contains it (although only uses it if it's native).
        setImmediate: false,
        // prevent webpack from injecting mocks to Node native modules
        // that does not make sense for the client
        dgram: 'empty',
        fs: 'empty',
        net: 'empty',
        tls: 'empty',
        child_process: 'empty'
    },
    externals: {
		// 	// 'echarts': 'echarts',
		// 	'vue': 'Vue',
		// 	'vue-router': 'VueRouter',
		// 	'vuex': 'Vuex',
		// 	'element-ui': 'ELEMENT',
			// "axios": 'axios',
      // 'jquery':'$',
    //   // 'XLSX':'xlsx'
    },
}
