What is Webpack?

What is Webpack?

Getting started with Webpack

Image for postSource: webpack.github.io

Webpack manages all the interdependent modules and files in your project. It bundles javascript and css files by merging the dependent code blocks into one so that you do not need to manage those on your own.

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

2. npm init -y into your project directory

3. npm install webpack -D

4. Add script in the following format to your package.json file

webpack <entry-point> <destination-file>

Alternatively, you can create a webpack.config.js file in your project to configure webpack and your build process accordingly.

Example config file :

module.exports = {
 entry: './path/to/my/entry/file.js',
 output: {
 path: path.resolve(__dirname, 'dist'),
 filename: 'my-first-webpack.bundle.js'
 }
};</span>

Since version 4.0.0, webpack does not require a configuration file to bundle your project, nevertheless it is incredibly configurable to better fit your needs.

An entry point indicates which module webpack should use to begin building out its internal dependency graph. webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

By default its value is ./src/index.js, but you can specify a different (or multiple entry points) by configuring the entry property in the webpack configuration.

The output property tells webpack where to emit the bundles it creates and how to name these files. It defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated file.

You can configure this part of the process by specifying an output field in your configuration

Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.

module.exports = {
 output: {
 filename: 'my-first-webpack.bundle.js'
 },
 module: {
 rules: [
 { test: /\.txt$/, use: 'raw-loader' }
 ]
 }
};</span>

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

By setting the mode parameter to either development, production or none, you can enable webpack's built-in optimizations that correspond to each environment. The default value is production.

webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). webpack needs Promise for import() and require.ensure(). If you want to support older browsers, you will need to load a polyfill before using these expressions.

Originally published at medium.com on January 3, 2019.