const {join} = require('path')
const webpack = require('webpack')
const nextRuntimeDotenv = require('next-runtime-dotenv')
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')

// The following modules will be pushed to the commons.js bundle
const commonModules = [
  '/node_modules/fbjs/',
  '/node_modules/lodash-es/',
  '/node_modules/marked/',
  '/node_modules/next/',
  '/node_modules/webpack/',

  '/components/hoc/',

  '/lib/session.js',

  '/pages/_error.js'
]

const withConfig = nextRuntimeDotenv({
  public: [
    'PUBLIC_URL',
    'DATAGOUV_API_URL',
    'DATAGOUV_API_KEY',
    'PUBLICATION_BASE_URL',
    'GEODATA_API_URL',
    'PIWIK_URL',
    'PIWIK_SITE_ID'
  ]
})

module.exports = withConfig({
  webpack(config, {dev, isServer}) {
    config.plugins.push(
      new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /fr/)
    )

    if (!dev && !isServer) {
      config.optimization.splitChunks.cacheGroups.shared = {
        name: 'commons',
        test: m => m.resource && commonModules.some(c =>
          m.resource.startsWith(join(__dirname, c))
        )
      }

      config.plugins.push(new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false,
        reportFilename: join(__dirname, 'reports/bundles.html'),
        defaultSizes: 'gzip'
      }))
    }

    const chunkFilename = dev ? '[name]' : '[name].[contenthash]'
    config.output.chunkFilename = isServer ? `${chunkFilename}.js` : `static/chunks/${chunkFilename}.js`

    config.resolve.alias = {
      // Replace lodash with lodash-es on client side.
      // This reduces the bundles sizes greatly and allows for webpack
      // scope hoisting in other dependencies.
      // Both lodash and lodash-es should be installed, as lodash-es
      // will not work server-side.
      lodash: 'lodash-es'
    }

    return config
  }
})

@@ -1325,187 +1325,11 @@
 %7D))%0A
+%0A
   
-  %7D%0A%0A    const chunkFilename = dev ? '%5Bname%5D' : '%5Bname%5D.%5Bcontenthash%5D'%0A    config.output.chunkFilename = isServer ? %60$%7BchunkFilename%7D.js%60 : %60static/chunks/$%7BchunkFilename%7D.js%60%0A%0A
     
@@ -1349,24 +1349,26 @@
 e.alias = %7B%0A
+  
       // Rep
@@ -1416,16 +1416,18 @@
 .%0A      
+  
 // This 
@@ -1489,16 +1489,18 @@
 k%0A      
+  
 // scope
@@ -1532,16 +1532,18 @@
 encies.%0A
+  
       //
@@ -1609,16 +1609,18 @@
 s%0A      
+  
 // will 
@@ -1647,16 +1647,18 @@
 .%0A      
+  
 lodash: 
@@ -1669,16 +1669,24 @@
 ash-es'%0A
+      %7D%0A
     %7D%0A%0A 

Move alias in client/prod only