Webpack
I would recommend Webpack which automates node module loading, dependencies, minification, and much more.
Installation
To use node modules in your project, first install node.js on your machine. The package management system NPM should be installed along the way. If you have already installed node.js, update Node.js and NPM to the latest version.
Usage
Initialization
Open your project in your code editor and inititialize npm by typing npm init -y
to the command line. Next, install webpack locally by typing npm install webpack webpack-cli --save-dev
. (--save-dev
means these dependencies are added to the devDependencies
section of your package.json
file which are not required for production)
Reorder Folder Structure
Follow the tree structure below to reconstruct your project folder:
yourProjectName
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
Create a dist
folder to hold all distribution files and move index.html
to that folder. Next, create a src
folder for all source files and move your js file to that folder. You should use the exact same file and folder names as appeared in the tree structure. (these are the default of Webpack but you can configure them later by editing webpack.config.js
)
Refactor dependencies
Remove all <script>
importations in index.html
and add <script src="main.js"></script>
before the </body>
tag. To import other node modules, add import statements at the beginning of your index.js
file. For example, if you want to import lodash
, just type import _ from 'lodash';
and proceed to use the _
in your index.js
file.
NOTE: Don't forget to first install the node package first before importing it in JS. To install lodash
locally, type npm install lodash
. Lodash will be automatically saved to your production dependencies in package.json
Run Webpack
Finally, run webpack by typing npx webpack
in your command line. You should see main.js
generated in the dist
folder for you by Webpack.
Additional resources
The above guide provides only the most basic way to use Webpack. To explore more useful use cases, go to the official tutorial of Webpack. It provides extremely comprehensive tutorials on topics such as asset management, output management, guides for development and production, etc.
Reference
https://webpack.js.org/guides/getting-started/