WebPack - Getting Started - Example

> (World Wide) Web - (W3|WWW) > Web - Building and Shipping > Web - WebPack

1 - About

Advertising

3 - Project Structure

3.1 - Without WebPack

index.html
<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/[email protected]"></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

3.2 - With Webpack

3.2.1 - WebPack Installation

npm install --save-dev webpack

3.2.2 - Dependency Installation

npm install --save myDependency
Advertising

3.2.3 - Script as a ES module declaring the dependency

src/index.js
import myDep from 'myDependency'
 
// ..... Use it

By stating what dependencies a module needs, webpack can use this information to build a dependency graph.

dist/index.html
<html>
   <head>
     <title>Getting Started</title>
   </head>
<body>
      <script src="bundle.js"></script>
</body>
</html>

3.2.4 - 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.

3.2.5 - WebPack Building with the WebPack configuration file

webpack.config.js
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
Advertising

3.2.6 - WebPack Building with npm

{
  ...
  "scripts": {
    "build": "webpack"
  },
  ...
}
  • Run with npm
npm run build

4 - Documentation / Reference

web/shipping/webpack/getting_started.txt · Last modified: 2019/02/16 17:40 by gerardnico