'use strict';
const path = require('path');
const webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

function resolve(dir) {
    return path.join(__dirname, dir);
}

const name = 'st vue'; // page title
const port = 9000; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
    publicPath:            process.env.PUBLIC_PATH,
    // publicPath:            process.env.NODE_ENV === 'production'
    //                        ? secondaryPath
    //                        : process.env.PUBLIC_PATH, // des: 部署应用包时的基本 二级目录时开启此处 URL author: wxy data: 2019/12/30
    // publicPath: './', //vueConf.baseUrl, // 根域上下文目录
    outputDir:             'dist', // 构建输出目录
    assetsDir:             process.env.ASSETS_DIR,
    // assetsDir: './', // 静态资源目录 (js, css, img, fonts)
    lintOnSave:            true, // 是否开启eslint保存检测，有效值：ture | false | 'error'
    runtimeCompiler:       true, // 运行时版本是否需要编译
    transpileDependencies: [], // 默认babel-loader忽略modealias_modules，这里可增加例外的依赖包名
    productionSourceMap:   false, // 是否在构建生产包时生成 sourceMap 文件，false将提高构建速度
    devServer:             {
        port:    port,
        open:    true,
        overlay: {
            warnings: false,
            errors:   true,
        },
        proxy:   {
            // change xxx-api/login => mock/login
            // detail: https://cli.vuejs.org/config/#devserver-proxy
            [process.env.VUE_APP_BASE_API]: {
                target:       process.env.VUE_APP_BASE_API_TARGET,
                changeOrigin: true,
                pathRewrite:  {
                    ['^' + process.env.VUE_APP_BASE_API]: '',
                },
            },
        },
    },
    pwa:                   {
        iconPaths: {
            favicon32:      process.env.VUE_APP_INDEX_TINY_ICON,
            favicon16:      process.env.VUE_APP_INDEX_TINY_ICON,
            appleTouchIcon: process.env.VUE_APP_INDEX_TINY_ICON,
            maskIcon:       process.env.VUE_APP_INDEX_TINY_ICON,
            msTileImage:    process.env.VUE_APP_INDEX_TINY_ICON,
        },
    },
    chainWebpack:          config => {
        config.resolve.alias
              .set('@', path.resolve(__dirname, './src'))
              .set('excelVendor', path.resolve(__dirname, './src/utils/excelVendor'));
        config.plugins.delete('preload');
        config.plugins.delete('prefetch');
        config.plugin('provide')
              .use(webpack.ProvidePlugin, [
                  {
                      'window.Quill': 'quill',
                      introJs:        'intro.js',
                  },
              ]);
    },
    configureWebpack:      config => {
        Object.assign(config, {
            name: name,
            // 开发生产共同配置
        });
        if (process.env.ENV === 'production') {

            let cssFilesArr = [
                `external/kityformula/kityformula/assets/styles/base.css`,
                `external/kityformula/kityformula/assets/styles/ui.css`,
                `external/kityformula/kityformula/assets/styles/scrollbar.css`,
            ];

            let jsFilesArr = [
                `external/js/vue@2.6.10.js`,
                `external/js/vue-router@3.1.3.js`,
                `external/js/element-ui@2.12.0.js`,
                `external/js/echarts@4.2.1.js`,
                `external/js/aliyun-upload-sdk/lib/es6-promise.min.js`,
                `external/js/aliyun-upload-sdk/lib/aliyun-oss-sdk-5.3.1.min.js`,
                `external/js/aliyun-upload-sdk/aliyun-upload-sdk-1.5.0.min.js`,
                `external/kityformula/kityformula/js/jquery-1.11.0.min.js`,
                `external/kityformula/kityformula/js/kitygraph.all.js`,
                `external/kityformula/kityformula/js/kity-formula-render.all.js`,
                `external/kityformula/kityformula/js/kity-formula-parser.all.min.js`,
                `external/kityformula/kityformula/js/kityformula-editor.all.min.js`,
            ];

            // 为生产环境修改配置...
            config.mode = 'production';
            Object.assign(config, {
                externals: {
                    'vue-router': 'VueRouter',
                    'element-ui': 'ELEMENT',
                    'echarts':    'echarts',
                    'vue':        'Vue',
                    // 'vuex': 'Vuex'
                },
                plugins:   [
                    ...config.plugins,
                    new HtmlWebpackPlugin({
                                              template:           path.join(__dirname, './src/utils/st/index.html'),//指定模板页面，根据指定的路径生成内存中的页面
                                              templateParameters: {
                                                  'BASE_URL':                process.env.PUBLIC_PATH,
                                                  'VUE_APP_INDEX_TINY_ICON': process.env.VUE_APP_INDEX_TINY_ICON,
                                                  'VUE_APP_INDEX_TITLE':     process.env.VUE_APP_INDEX_TITLE,
                                                  'cssVendor':               cssFilesArr,
                                                  'jsVendor':                jsFilesArr,
                                              },
                                              filename:           'index.html', //指定内存中生成的页面的名称
                                         /*     inject: true,
                                              favicon: process.env.BASE_URL+ 'favicon-saas.ico'*/
                                          }),
                    new CompressionPlugin({
                                              test:                 /\.js$|\.html$|.\css/, // 匹配文件名 ttf
                                              threshold:            10240, // 对超过10k的数据压缩
                                              deleteOriginalAssets: false, // 不删除源文件
                                          }),

                ],
            });
        } else {
            // 为开发环境修改配置...
            config.mode = 'development';
        }

    },
    css:                   {
        // 当为true时，css文件名可省略 module 默认为 false
        modules:       false,
        // 是否将组件中的 CSS 提取至一个独立的 CSS 文件中,当作为一个库构建时，你也可以将其设置为 false 免得用户自己导入 CSS
        // 默认生产环境下是 true，开发环境下是 false
        extract:       false,
        // 是否为 CSS 开启 source map。设置为 true 之后可能会影响构建的性能
        sourceMap:     false,
        //向 CSS 相关的 loader 传递选项(支持 css-loader postcss-loader sass-loader less-loader stylus-loader)
        loaderOptions: {
            css:  {},
            less: {},
            sass: {
                /*data: `@import "@/assets/css/main.scss";`*/
            },
        },
    },

    /*configureWebpack:      {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name:      name,
    resolve:   {
        alias: {
            '@':           resolve('src'),
            'excelVendor': resolve('src/utils/excelVendor'),
        },
    },
    externals: {
        'vue':        'Vue',
        'vue-router': 'VueRouter',
        'element-ui': 'ELEMENT',
        'echarts':    'echarts',
    },
    plugins:   [
        new CompressionPlugin({
                                  test:                 /\.js$|\.html$|.\css/, // 匹配文件名 ttf
                                  threshold:            10240, // 对超过10k的数据压缩
                                  deleteOriginalAssets: false, // 不删除源文件
                              }),
    ],
},*/

    /*chainWebpack(config) {
      const cdn = {
        // inject tinymce into index.html
        // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
        js: ['https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js']
      }
      config.plugin('html')
        .tap(args => {
          args[0].cdn = cdn
          return args
        })
      config.plugins.delete('preload') // TODO: need test
      config.plugins.delete('prefetch') // TODO: need test

      // set svg-sprite-loader
      config.module
        .rule('svg')
        .exclude.add(resolve('src/icons'))
        .end()
      config.module
        .rule('icons')
        .test(/\.svg$/)
        .include.add(resolve('src/icons'))
        .end()
        .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
          symbolId: 'icon-[name]'
        })
        .end()

      // set preserveWhitespace
      config.module
        .rule('vue')
        .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
          options.compilerOptions.preserveWhitespace = true
          return options
        })
        .end()

      config
        // https://webpack.js.org/configuration/devtool/#development
        .when(process.env.ENV === 'development',
          config => config.devtool('cheap-source-map')
        )

      config
        .when(process.env.ENV !== 'development',
          config => {
            config
              .plugin('ScriptExtHtmlWebpackPlugin')
              .after('html')
              .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
                inline: /runtime\..*\.js$/
              }])
              .end()
            config
              .optimization.splitChunks({
                chunks: 'all',
                cacheGroups: {
                  libs: {
                    name: 'chunk-libs',
                    test: /[\\/]node_modules[\\/]/,
                    priority: 10,
                    chunks: 'initial' // only package third parties that are initially dependent
                  },
                  elementUI: {
                    name: 'chunk-elementUI', // split elementUI into a single package
                    priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                    test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                  },
                  commons: {
                    name: 'chunk-commons',
                    test: resolve('src/components'), // can customize your rules
                    minChunks: 3, //  minimum common number
                    priority: 5,
                    reuseExistingChunk: true
                  }
                }
              })
            config.optimization.runtimeChunk('single')
          }
        )
    }*/
};
