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 -y
to 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.js
in which you will import other modules:
const printHello = require('./print-hello');
printHello();
- Create a sample
print-hello.js
module:
module.exports = function() {
console.log('Hello World!');
}
- 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.
- Open your
package.json
, and replacescripts
with the following command:
"scripts": {
"start": "webpack --mode production -w"
},
- And finally run the script watch
app.js
and generate the_bundle.js
file by running:npm start
. - Enjoy coding!