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:
- In your project root, run
npm init -yto initialize an npm project - Download the Webpack module bundler:
npm install webpack webpack-cli - 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).
- Create a
<project-root>/app.jsin which you will import other modules:
const printHello = require('./print-hello');
printHello();
- Create a sample
print-hello.jsmodule:
module.exports = function() {
console.log('Hello World!');
}
- Create a
<project-root>/webpack.config.jsand 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.jsis where you will write your JS code. It will import other modules as shown above. - output
_bundle.jsis your final bundle generated by webpack. This is what your html will see at the end.
- Open your
package.json, and replacescriptswith the following command:
"scripts": {
"start": "webpack --mode production -w"
},
- And finally run the script watch
app.jsand generate the_bundle.jsfile by running:npm start. - Enjoy coding!