Webpack and Babel setup for Javascript

Setup package.json by running:

npm init -y

Add packages:

npm install --save-dev \
  @babel/core          \
  @babel/preset-env    \
  babel-loader         \
  webpack              \
  webpack-cli

Create webpack.config.js with index.js as your main, and bundle.js as output:

const webpack = require('webpack');
const path = require('path');

const config = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname),
    filename: 'bundle.js',
    library: 'SomeClass',
    libraryTarget: 'var',
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }
};

module.exports = config;

Create .babelrc with:

{
  presets: [
    [
      '@babel/preset-env',
      {
        modules: false
      }
    ]
  ]
}

Write your index.js file:

class SomeClass {
  constructor() {
    console.log('Hello')
  }
}

module.exports = SomeClass

And your index.html file:

<!doctype html>
<html>
  <head>
    <title></title>
    <meta charset="utf-8" />

    <script src="bundle.js"></script>
  </head>
  <body>
    <footer>
      <script>
        window.addEventListener('DOMContentLoaded', function(_event) {
          new SomeClass()
        })
      </script>
    </footer>

  </body>
</html>

Run it with:

npx webpack --watch

Open your index.html page to see results:

open index.html