webpack is used to compile JavaScript modules. Once installed, you can interface with webpack either from its CLI or API.
Basic Setup
First let's create a directory, initialize npm, install webpack locally, and install the webpack-cli (the tool used to run webpack on the command line):
mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
Now we'll create the following directory structure, files and their contents:
project
webpack-demo
|- package.json
|- index.html
|- /src
|- index.js
src/index.js
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash@4.16.6"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
We also need to adjust our package.json file in order to make sure we mark our package as private, as well as removing the main entry. This is to prevent an accidental publish of your code.
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
},
"dependencies": {}
}
In this example, there are implicit dependencies between the <script> tags. Our index.js file depends on lodash being included in the page before it runs. This is because index.js never explicitly declared a need for lodash; it just assumes that the global variable _ exists.
There are problems with managing JavaScript projects this way:
It is not immediately apparent that the script depends on an external library.
If a dependency is missing, or included in the wrong order, the application will not function properly.
If a dependency is included but not used, the browser will be forced to download unnecessary code.
Let's use webpack to manage these scripts instead.
Creating a Bundle
First we'll tweak our directory structure slightly, separating the "source" code (/src) from our "distribution" code (/dist). The "source" code is the code that we'll write and edit. The "distribution" code is the minimized and optimized output of our build process that will eventually be loaded in the browser. Tweak the directory structure as follows:
project
webpack-demo
|- package.json
|- /dist
|- index.html
|- index.html
|- /src
|- index.js
To bundle the lodash dependency with index.js, we'll need to install the library locally:
npm install --save lodash
References:
https://webpack.js.org/guides/getting-started/
No comments:
Post a Comment