Master Webpack: From Basics to Advanced Configuration
This article introduces webpack, explains its advantages, guides through installation, configuration, loaders, plugins, and practical usage examples, covering module formats, shimming, extracting CSS, CDN integration, and integration with tools like Gulp, providing a comprehensive beginner‑to‑intermediate tutorial.
What is webpack?
Webpack is a popular module loader and bundler that treats JavaScript (including JSX), CoffeeScript, styles (including Less/Sass), images and other assets as modules.
It allows you to require modules with require(...) and automatically applies appropriate loaders to compile them.
Although you may not use it in your own project, many modern React‑related repositories on GitHub rely on webpack.
Official site: http://webpack.github.io/ and documentation: http://webpack.github.io/docs/.
Advantages of webpack
Its main benefits include:
Supports CommonJS syntax while also fully supporting AMD/CMD, easing migration of legacy code.
Not limited to JavaScript; other assets can be modularized.
Convenient development: can replace parts of Grunt/Gulp for bundling, minification, image base64 conversion, etc.
Strong extensibility with a mature plugin system, e.g., React hot‑loader support.
For AMD/CMD modules you normally write:
define(['package/lib'], function (lib) {
function foo(){
lib.log('hello world!');
}
return {
foo: foo
};
});Webpack also supports the same pattern in CommonJS without the define wrapper:
var someModule = require("someModule");
var anotherModule = require("anotherModule");
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
exports.asplode = function () {
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
};Installation and Configuration
1. Installation
npm install webpack -g
npm init
npm install webpack --save-dev2. Configuration
Each project needs a webpack.config.js file, similar to a gulpfile.js or Gruntfile.js. A typical example:
var webpack = require('webpack');
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
module.exports = {
// plugins
plugins: [commonsPlugin],
// entry files
entry: {
index: './src/js/page/index.js'
},
// output configuration
output: {
path: 'dist/js/page',
filename: '[name].js'
},
// loaders
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.js$/, loader: 'jsx-loader?harmony' },
{ test: /\.scss$/, loader: 'style!css!sass?sourceMap' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
]
},
// resolve options
resolve: {
root: 'E:/github/flux-example/src',
extensions: ['', '.js', '.json', '.scss'],
alias: {
AppStore: 'js/stores/AppStores.js',
ActionType: 'js/actions/ActionType.js',
AppAction: 'js/actions/AppAction.js'
}
}
};Key points:
plugins : the example uses CommonsChunkPlugin to extract shared code into common.js.
entry and output define the input files and the generated bundle names.
module.loaders specify which loader processes each file type.
resolve configures module lookup paths, file extensions and aliases.
Install loaders via npm, e.g., npm install url-loader -save-dev. The ?limit=8192 option in url-loader inlines images smaller than 8 KB as base64 data URLs.
Running webpack
Execute webpack from the command line:
webpack --display-error-details
webpack --config custom.config.js
webpack --watch
webpack -p
webpack -dThe -p flag enables production optimizations such as minification, often reducing bundle size dramatically.
Module Inclusion
HTML
Include the generated bundles directly in your HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script src="dist/js/page/common.js"></script>
<script src="dist/js/page/index.js"></script>
</body>
</html>JavaScript
Modules can be written in CommonJS and may import uncompiled assets (JSX, Sass, CoffeeScript) as long as the appropriate loaders are configured.
require('../../css/reset.scss'); // load base styles
require('../../css/allComponent.scss'); // load component styles
var React = require('react');
var AppWrap = require('../component/AppWrap');
var createRedux = require('redux').createRedux;
var Provider = require('redux/react').Provider;
var stores = require('AppStore');
var redux = createRedux(stores);
var App = React.createClass({
render: function () {
return (
<Provider redux={redux}>
{function(){ return <AppWrap />; }}
</Provider>
);
}
});
React.render(<App />, document.body);Additional Tips
1. Shimming
For non‑AMD modules you can use exports-loader:
{ test: require.resolve("./src/js/tool/swipe.js"), loader: "exports?swipe" }Then simply require('./tool/swipe.js'); swipe(); 2. Custom Commons Chunk
Configure multiple entry points and extract shared code with CommonsChunkPlugin:
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3",
ap1: "./admin/page1",
ap2: "./admin/page2"
},
output: {
filename: "[name].js"
},
plugins: [
new CommonsChunkPlugin("admin-commons.js", ["ap1", "ap2"]),
new CommonsChunkPlugin("commons.js", ["p1", "p2", "admin-commons.js"])
]
};3. Extracting CSS
Use extract-text-webpack-plugin to output CSS files instead of embedding them in JavaScript:
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
plugins: [commonsPlugin, new ExtractTextPlugin("[name].css")],
// other configuration …
};4. CDN / External Files
Define externals to load libraries from a CDN while keeping require('jquery') functional:
externals: {
"jquery": "jQuery"
}Make sure the CDN script is loaded before the webpack bundle.
5. Gulp Integration
gulp.task("webpack", function(callback) {
webpack({
// configuration
}, function(err, stats) {
if (err) throw new gutil.PluginError("webpack", err);
gutil.log("[webpack]", stats.toString({}));
callback();
});
});6. React Optimizations
Install React via npm install react to reduce bundle size.
Use react-hot-loader together with webpack-dev-server for hot module replacement.
This guide provides a comprehensive introduction to webpack, covering its core concepts, configuration options, and practical integration techniques.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
