Node-style require for in-browser javascript? [closed]

I realize there may be beginners looking to organize their code. This is 2022, and if you’re considering a modular JS app, you should get started with npm and Webpack right now.

Here are a few simple steps to get started:

  1. In your project root, run npm init -y to initialize an npm project
  2. Download the Webpack module bundler: npm install webpack webpack-cli
  3. Create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>App</title>
</head>
<body>
    
    <script src="_bundle.js"></script>
</body>
</html>

Pay special attention to _bundle.js file – this will be a final JS file generated by webpack, you will not modify it directly (keep reading).

  1. Create a <project-root>/app.js in which you will import other modules:
const printHello = require('./print-hello');

printHello();
  1. Create a sample print-hello.js module:
module.exports = function() {
    console.log('Hello World!');
}
  1. Create a <project-root>/webpack.config.js and copy-paste the following:
var path = require('path');

module.exports = {
  entry: './app.js',
  output: {
    path: path.resolve(__dirname),
    filename: '_bundle.js'
  }
};

In the code above, there are 2 points:

  • entry app.js is where you will write your JS code. It will import other modules as shown above.
  • output _bundle.js is your final bundle generated by webpack. This is what your html will see at the end.
  1. Open your package.json, and replace scripts with the following command:
  "scripts": {
    "start": "webpack --mode production -w"
  },
  1. And finally run the script watch app.js and generate the _bundle.js file by running: npm start.
  2. Enjoy coding!

Leave a Comment