What is webpack?
Webpack is a powerful module bundler for JavaScript applications. It processes applications by internally building a dependency graph which maps every module your project needs and generates one or more bundles. It is highly extensible via loaders and plugins, and it's designed to manage, transform, and bundle frontend assets like JavaScript, CSS, and images.
What are webpack's main functionalities?
Module Bundling
Webpack bundles all the JavaScript files and other assets like CSS and images into a single output file. The code sample shows a basic webpack configuration defining an entry point and the output bundle.
module.exports = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
}
};
Loaders
Loaders allow webpack to process different types of files and convert them into modules that can be included in your bundle. The code sample demonstrates how to use loaders to handle .txt and .css files.
module.exports = {
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }
]
}
};
Plugins
Plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management, and environment variable injection. The code sample shows how to use the HtmlWebpackPlugin to generate an index.html file with the bundled assets injected.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })]
};
Development Server
Webpack provides a development server that can be used to serve your application during development. It supports live reloading. The code sample configures the webpack development server to serve files from the 'dist' directory.
module.exports = {
devServer: {
contentBase: './dist',
open: true
}
};
Code Splitting
Code splitting allows you to split your code into various bundles which can then be loaded on demand or in parallel. The code sample shows how to split the application and vendor code into separate bundles.
module.exports = {
entry: {
app: './src/app.js',
vendor: './src/vendor.js'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist'
}
};
Other packages similar to webpack
rollup
Rollup is a module bundler for JavaScript which uses a flat bundle approach that's more efficient for libraries and applications with a complex module structure. It's known for its tree-shaking capabilities, which eliminate unused code.
parcel
Parcel is a web application bundler that offers a zero-configuration setup. It's known for its fast bundle times and out-of-the-box support for many file types without the need for additional plugins or loaders.
browserify
Browserify lets you require('modules') in the browser by bundling up all of your dependencies. It's been around longer than webpack and has a simpler approach, but it lacks some of the more advanced features and optimizations that webpack offers.
fuse-box
FuseBox is a bundler/module loader that combines the power of webpack, JSPM, and SystemJS. It introduces a streamlined workflow and has a powerful API. It's known for its speed and simplicity.
Install
npm install --save-dev webpack
Introduction
The README reflects webpack v2.x, webpack v1.x documentation can be found here.
webpack is a bundler for modules. The main purpose is to bundle JavaScript
files for usage in a browser, yet it is also capable of transforming, bundling,
or packaging just about any resource or asset.
TL;DR
- Bundles ES Modules, CommonJS and AMD modules (even combined).
- Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time).
- Dependencies are resolved during compilation, reducing the runtime size.
- Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc.
- Highly modular plugin system to do whatever else your application requires.
Get Started
Check out webpack's quick Get Started guide and the other guides.
Concepts
webpack has a rich plugin
interface. Most of the features
within webpack itself use this plugin interface. This makes webpack very
flexible.
webpack enables use of loaders to preprocess files. This allows you to bundle
any static resource way beyond JavaScript. You can easily write your own
loaders using Node.js.
Loaders are activated by using loadername!
prefixes in require()
statements,
or are automatically applied via regex from your webpack configuration.
Files
Name | Status | Description |
---|
raw-loader | | Loads raw content of a file (utf-8) |
val-loader | | Executes code as module and consider exports as JS code |
url-loader | | Works like the file loader, but can return a Data Url if the file is smaller than a limit |
file-loader | | Emits the file into the output folder and returns the (relative) url |
JSON
Name | Status | Description |
---|
| | Loads a JSON file (included by default) |
| | Loads and transpiles a JSON 5 file |
| | Loads and transpiles a CSON file |
Transpiling
Name | Status | Description |
---|
<script> | | Executes a JavaScript file once in global context (like in script tag), requires are not parsed |
| | Loads ES2015+ code and transpiles to ES5 using Babel |
| | Loads ES2015+ code and transpiles to ES5 using Traceur |
| | Loads TypeScript like JavaScript |
| | Loads CoffeeScript like JavaScript |
Templating
Name | Status | Description |
---|
| | Exports HTML as string, require references to static resources |
| | Loads Pug templates and returns a function |
| | Loads Jade templates and returns a function |
| | Compiles Markdown to HTML |
| | Loads and transforms a HTML file using PostHTML |
| | Compiles Handlebars to HTML |
Styling
Name | Status | Description |
---|
<style> | | Add exports of a module as style to DOM |
| | Loads CSS file with resolved imports and returns CSS code |
| | Loads and compiles a LESS file |
| | Loads and compiles a SASS/SCSS file |
| | Loads and compiles a Stylus file |
| | Loads and transforms a CSS/SSS file using PostCSS |
Linting && Testing
Name | Status | Description |
---|
| | Tests with mocha (Browser/NodeJS) |
| | PreLoader for linting code using ESLint |
| | PreLoader for linting code using JSHint |
| | PreLoader for code style checking using JSCS |
Frameworks
Name | Status | Description |
---|
| | Loads and compiles Vue Components |
| | Process HTML & CSS with preprocessor of choice and require() Web Components like first-class modules |
| | Loads and compiles Angular 2 Components |
| | Riot official webpack loader |
Performance
webpack uses async I/O and has multiple caching levels. This makes webpack fast
and incredibly fast on incremental compilations.
Module Formats
webpack supports ES2015+, CommonJS and AMD modules out of the box. It performs clever static
analysis on the AST of your code. It even has an evaluation engine to evaluate
simple expressions. This allows you to support most existing libraries out of the box.
webpack allows you to split your codebase into multiple chunks. Chunks are
loaded asynchronously at runtime. This reduces the initial loading time.
webpack can do many optimizations to reduce the output size of your
JavaScript by deduplicating frequently used modules, minifying, and giving
you full control of what is loaded initially and what is loaded at runtime
through code splitting. It can also make your code chunks cache
friendly by using hashes.
Contributing
Most of the time, if webpack is not working correctly for you it is a simple configuration issue.
If you are still having difficulty after looking over your configuration carefully, please post
a question to StackOverflow with the webpack tag. Questions
that include your webpack.config.js and relevant files are more likely to receive responses.
If you have discovered a bug or have a feature suggestion, feel free to create an issue on Github.
If you create a loader or plugin, please consider open sourcing it, putting it
on npm and following the x-loader
, x-webpack-plugin
convention.
You are also welcome to correct any spelling mistakes or any language issues.
If you want to discuss something or just need help, here is our Gitter room.
License
Core Team
Most of the core team members, webpack contributors and contributors in the ecosystem do this open source work in their free time. If you use webpack for a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth.
This is how we use the donations:
- Allow the core team to work on webpack
- Thank contributors if they invested a large amount of time in contributing
- Support projects in the ecosystem that are of great value for users
- Support projects that are voted most (work in progress)
- Infrastructure cost
- Fees for money handling
Premium Partners
Other Backers and Sponsors
Before we started using OpenCollective, donations were made anonymously. Now that we have made the switch, we would like to acknowledge these sponsors (and the ones who continue to donate using OpenCollective). If we've missed someone, please send us a PR, and we'll add you to this list.
Google Angular Team, Architects.io,
Become a sponsor and get your logo on our README on Github with a link to your site.
Backers
Become a backer and get your image on our README on Github with a link to your site.
Thanks to
(In chronological order)
- @google for Google Web Toolkit (GWT), which aims to compile Java to JavaScript. It features a similar Code Splitting as webpack.
- @medikoo for modules-webmake, which is a similar project. webpack was born because I wanted Code Splitting for modules-webmake. Interestingly the Code Splitting issue is still open (thanks also to @Phoscur for the discussion).
- @substack for browserify, which is a similar project and source for many ideas.
- @jrburke for require.js, which is a similar project and source for many ideas.
- @defunctzombie for the browser-field spec, which makes modules available for node.js, browserify and webpack.
- Every early webpack user, which contributed to webpack by writing issues or PRs. You influenced the direction...
- @shama, @jhnns and @sokra for maintaining this project
- Everyone who has written a loader for webpack. You are the ecosystem...
- Everyone I forgot to mention here, but also influenced webpack.