Webpack setup basics

First, we will install webpack, this is done using the commands:



yarn add webpack webpack-cli -Dif you are using the yarn package manager

npm i webpack webpack-cli --save-dev, for the npm package manager



Webpack is configured using the configuration file webpack.config.js, which is stored in the root directory of the project.



An example of a config file:



const path = require('path')
module.exports = {
   watch: true,
   entry: "./src/index.js",
   output: {
       filename: "bundle.js",
       path: path.resolve(__dirname,'build'),
       publicPath: "/"
   }
};


The initial configuration is as follows:



  • watch - makes webpack watch for changes in files and rebuild;
  • entry - Indicates the entry point to the project, and where to start building the graph of internal project dependencies;
  • output - Specifies the path where the created file will be located and how it will be named;


You also need to install webpack-dev-server, which you need to develop and debug the application.



yarn add webpack-dev-serverfor package manager yarn or

npm i webpack-dev-serverif using npm



To configure webpack-dev-server add devServer in our config file.



Parameters for webpack-dev-server:



module.exports = {
    //...
    devServer: {
        port: 8000,
        historyApiFallback: true,
        hot: true,
    },
};


We also need to add / replace the project startup script in our package.json file:



"start": "webpack-dev-server --mode development",


and a script for building the build:



"build": "webpack --mode production"


Bootloaders



Loaders are special modules that are used to "load" other modules. They also allow you to preprocess files as they are imported or "loaded".



Loaders can convert files like TypeScript to JavaScript, sass to css. They may even allow us to do things like import CSS and HTML files directly into our JavaScript modules. To use them, you need to register the necessary loaders in the module.rules section of the configuration file.



Loader examples:



  • babel-loader - uses babel to load ES2015 files.
  • file-loader - for loading various files (images, music tracks, etc.) into the output directory
  • style-loader - used to load styles
  • css-loader - enables loading style files
  • @ svgr / webpack - a loader that allows you to use svg images as jsx elements


To use babel-loader you need to installbabel/ core . Also install the presetbabel/ preset-env , which compiles ES2015 + to ES5 by automatically detecting the plugins and polyfiles needed by Babel. Next, create a .babelrc file and add the previously installed preset to it.



{
 "presets": [
   "@babel/preset-env"
 ]
}


Now let's add a loader to our configuration for converting Javascript files. This will allow us to use ES2015 + syntax in our code (which will automatically convert to ES5 in the final build).



{
   test: /\.(js|jsx)$/,
   exclude: /node_modules/,
   use: {
       loader: 'babel-loader',
   },
},


Example configuration with file-loader



{
   test: /\.(png|jpe?g|gif)$/i,
   use: [
       {
           loader: 'file-loader',
       },
   ],
},


Example configuration for the @ svgr / webpack loader



{
   test : /\.(svg)$/,
   use: [
       {
           loader: "@svgr/webpack"
       }
   ]
}


Plugins



Plugins are the backbone of webpack, as essentially all of its work is built on the plugin system. They greatly expand the capabilities of bootloaders.



Loaders perform preprocessing of files of any format. They work at the level of individual files during or prior to package creation. After the loaders are finished, the plugins turn. Plugins usually only perform one function.



To use them, you need to add the necessary plugins in the plugins section of the configuration file.



Examples of plugins:



  • html-webpack-plugin - used to create html files
  • copy-webpack-plugin - Copies individual files or entire directories that already exist to the build directory.
  • definePlugin - allows you to create global constants
  • HotModuleReplacementPlugin - turns on HMR mode, updates only the part that has changed, without completely reloading the application.


Example configuration with added plugins:



plugins: [
   new webpack.HotModuleReplacementPlugin(),
   new webpack.DefinePlugin({
       'process.env': JSON.stringify(process.env),
   }),
   new HtmlWebpackPlugin({
       template: "./public/index.html",
   }),
   new CopyWebpackPlugin({
       patterns: [
           { from: './public/favicon.ico', to: './public'}
       ]
   }),
],


We will also add the UglifyjsWebpackPlugin plugin, which minifies the js code, for this you need to install uglifyjs-webpack-plugin and add it in the optimization section



optimization: {
   minimizer: [new UglifyJsPlugin()]
},



All Articles