Blog>
Snippets

Adapting Webpack Configuration for ESM Support

Provide a practical example of updating a Webpack configuration to handle ESM modules in a Redux project.
const path = require('path');

module.exports = {
  // Configuration Mode
  mode: 'development',
  // Entry file
  entry: './src/index.js',
  // Output configuration
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  // Module Loaders and Rules
  module: {
    rules: [
      {
        test: /\.m?js$/, // Match both .js and .mjs files
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader', // Use Babel for transpiling
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  // Resolve both .js and .mjs files without specifying the extension
  resolve: {
    extensions: ['.js', '.mjs']
  },
  // Dev Server configuration for development convenience
  devServer: {
    static: './dist'
  }
};
This webpack configuration example includes the necessary setup for handling ESM modules. It specifies the entry and output points, utilizes Babel for transpiling modern JavaScript, and configures the module resolution to recognize both .js and .mjs file extensions. The `devServer` is also configured for serving the project during development.