const path = require('path')
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')

const rules = require('./webpack.rules.js')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')

const appName = 'side_menu'
const buildMode = process.env.NODE_ENV
const isDev = buildMode === 'development'

module.exports = {
  target: 'web',
  mode: buildMode,
  devtool: false,
  entry: {
    menu: path.resolve(path.join('src', 'menu.js')),
    admin: path.resolve(path.join('src', 'admin.js')),
    user: path.resolve(path.join('src', 'user.js')),
  },
  output: {
    path: path.resolve('./js'),
    publicPath: path.join('/apps/', appName, '/js/'),

    // Output file names
    filename: `${appName}-[name].js?v=[contenthash]`,
    chunkFilename: `${appName}-[name].js?v=[contenthash]`,

    // Clean output before each build
    clean: true,
  },

  optimization: {
    chunkIds: 'named',
    splitChunks: {
      automaticNameDelimiter: '-',
      minSize: 10000,
      maxSize: 250000,
    },
    minimize: !isDev,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          output: {
            comments: false,
          }
        },
        extractComments: true,
      }),
    ],
  },

  module: {
    rules: Object.values(rules),
  },

  plugins: [
    new VueLoaderPlugin(),

    // Make sure we auto-inject node polyfills on demand
    // https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-nodejs-polyfills-removed
    new NodePolyfillPlugin({
      // Console is available in the web-browser
      excludeAliases: ['console'],
    }),

    // @nextcloud/moment since v1.3.0 uses `moment/min/moment-with-locales.js`
    // Which works only in Node.js and is not compatible with Webpack bundling
    // It has an unused function `localLocale` that requires locales by invalid relative path `./locale`
    // Though it is not used, Webpack tries to resolve it with `require.context` and fails
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.[/\\]locale$/,
      contextRegExp: /moment[/\\]min$/,
    }),

    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    }),
  ],

  resolve: {
    extensions: ['.*', '.mjs', '.js', '.vue'],
    symlinks: false,
    // Ensure npm does not duplicate vue dependency, and that npm link works for vue 3
    // See https://github.com/vuejs/core/issues/1503
    // See https://github.com/nextcloud/nextcloud-vue/issues/3281
    alias: {
      'vue$': path.resolve('./node_modules/vue')
    },
  },
}

