About
A summary of the getting started page of Webpack.
See also: How to develop, publish and use a javascript library ?
Articles Related
Project Structure
Without WebPack
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/myDependency@version"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
In this setup:
- The dependencies are not explicit declared. It is not immediately apparent that the index.js depends on an the library myDependency.
- The dependency order is not enforced (If a dependency is missing, or included in the wrong order, the application will not function properly.)
- The unused dependencies will be still downloaded.
- Global scope pollution may occur
With Webpack
WebPack Installation
- Install WebPack
npm install --save-dev webpack
Dependency Installation
- Install the dependency with Javascript - npm (Node package manager)
npm install --save myDependency
Script as a ES module declaring the dependency
- Import it in your script
import myDep from 'myDependency'
// ..... Use it
By stating what dependencies a module needs, webpack can use this information to build a dependency graph.
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
WebPack Building
- Build bundle.js from index.js
cd ProjectDirectory
.\node_modules\.bin\webpack.cmd src/index.js dist/bundle.js
Hash: 3f6631d7336776a04600
Version: webpack 3.6.0
Time: 2450ms
Asset Size Chunks Chunk Names
bundle.js 744 kB 0 [emitted] [big] main
[169] ./src/index.js 174 bytes {0} [built]
+ 459 hidden modules
- Open the index.html file that include the build script bundle.js and you must get the same output than without webpack.
WebPack Building with the WebPack configuration file
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
- Run the build again with the config
cd ProjectDirectory
.\node_modules\.bin\webpack.cmd --config webpack.config.js
WebPack Building with npm
{
...
"scripts": {
"build": "webpack"
},
...
}
- Run with npm
npm run build