Awesome Webpack
What is Webpack
- Module bundler
- Understands CJS and AMD
- Creates one or many bundles
- Treats every asset as a module
- Gives you hooks to transform modules
- Gives you hooks into the bundling process
How to invoke webpack
- webpack for building once for development
- webpack -p minification
- webpack --watch for continuous incremental build in development
Module style
CommonJS
AMD
ES6 modules (using es6-loader)
var someModule = require("./someModule.js");
module.exports = 42;
define(["./someModule.js"] , function (someModule) {
return 42;
});
import someModule from "./someModule.js";
export default 42;
Single Entry
greeter.js
module.exports = {
greet: function (name) {
return 'Hello ' + name;
}
};
var greeter = require('./greeter');
console.log(greeter.greet('John'));
entry.js
$ webpack entry.js bundle.js
Multiple Entries
entry1.js
var greeter = require('./greeter');
console.log(greeter.greet('Smith'));
var greeter = require('./greeter');
console.log(greeter.greet('John'));
entry2.js
module.exports = {
entry: {
entry1: './entry1',
entry2: './entry2'
},
output: {
path: 'output',
filename: 'bundle-[name].js'
}
};
webpack.config.js
Module Resolution
module.exports = {
entry: './entry',
output: {
path: 'output',
filename: 'bundle.js'
},
resolve: {
modulesDirectories: [
'bower_components',
'node_modules'
]
}
};
Code Spiltting
var webpack = require('webpack');
var commonsPlugin =
new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
entry: {
Profile: './profile.js',
Feed: './feed.js'
},
output: {
path: 'build',
filename: '[name].js' // Template based on keys in entry above
},
plugins: [commonsPlugin]
};
Webpack config file
In your HTML page
<script src="common.js"></script>
<script src="profile.js"></script>
<script src="feed.js"></script>
Load On Demand
require-ensure
require.ensure(["module-a", "module-b"], function(require) {
var a = require("module-a");
// ...
});
ensures that every dependency in dependencies can be synchronously required when calling the callback.
But websites are more than just JavaScript:

Wouldn't it be nice if we could all just require() them?
That's were loaders come in...
Loaders
Loaders are transformations that are applied on files. They preprocess files. For instance they can transform CoffeeScript to JavaScript.
raw-loader
Turns ...
... into ...
<div class="hello-world">
<h1>Hello World</h1>
</div>
module.exports = "<div class=\"hello-world\">\n <h1>Hello world</h1>\n</div>";
How are loaders applied?
Inlined
Via Config
var HelloWorld = {
template: require("raw!./HelloWorld.html"),
styles: require("raw!./HelloWorld.css")
};
module.exports = {
// ...
module: {
loaders: [
{ test: /\.html$|\.css$/i, loader: "raw" }
]
}
// ...
};
Available loaders
- sass loader
- haml loader
- expose loader
- babel loader
- ngtemplate
webpack
By jingliu
webpack
- 464