An Introduction to webpack
What is Webpack?
Webpack is a module bundler for modern JavaScript applications. It takes your code, transforms and bundles it, then returns a new ‘compiled’ version. It’s also known as module bundler. Webpack is not limited to be used on the frontend, but it’s also useful in backend Node.js development as well.
What can Webpack do for you
- It can run Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.
- It Can run a development webserver.
- Bundle your all resources.
- Transpile CoffeeScript to JavaScript
- Concatenating library files
- Image optimization
- Compile SCSS to CSS
And many more …
System Requirements and Installation
Ensure you have [nodejs] installed
Initializing package.json by using npm init
command.
Run the following command
npm install --save-dev webpack
After successfully installed create a webpack config file in your project root directory
webpack.config.js
(This is the main configuration file for webpack)
Now Configure webpack.config.js
There are three key parts to a basic Webpack configuration.
entry — the starting point of your application
loaders — the transformations you want to make on your code
output — where you want your compiled code to go
THE ENTRY POINT
By default the entry point is ./src/index.js
This simple example uses the ./index.js
file as a starting point:
module.exports = {
/*...*/
entry: './index.js'
/*...*/
}
THE OUTPUT
By default the output is generated in ./dist/main.js
. This example puts the output bundle into app.js
module.exports = {
/*...*/
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
}
/*...*/
}
And LOADERS
webpack allows you to use import or require statements in your JavaScript code to not just include other JavaScript, but any kind of file, for example CSS.
Webpack handle all our dependencies, not just JavaScript, and loaders are one way to do that.
For example, in your code you can use:
import 'style.css'
by using this loader configuration:
module.exports = {
/*...*/
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' },
}]}
/*...*/
}
A loader can have options:
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'css-loader',
options: {
modules: true
}}]}]}
/*...*/
}
There are lot’s of loader check their official site https://webpack.js.org/loaders/
Plugins
Plugins are like loader check their official site — https://webpack.js.org/plugins/
webpack.config.js file example — webpack.config.js
Check official Documentation — https://webpack.js.org/concepts/
Originally published at www.rajibkarmaker.me on January 16, 2018.