Wednesday, May 20, 2020

Webpack

Webpack is a module bundler, its main purpose is to bundle all the dependent files into a single .js file which helps optimize the page load. Apart from bundling webpack can also be used as a task runner by configuring a sequence of tasks in the build process like cleanup target folder, bundle files, copy files etc. Webpack by itself is a big topic, in this post we shall see the minimal configuration required in webpack to bundle and load a React Application.

Webpack is configuration driver, remember we created a file in the webpack.config.js previous Hello World post, this is the webpack configuration file. The most minimal webpack configuration includes and entry (input) and an output.

Entry & Output
The entry config entry is set to the starting point of the application, in our previous example we set it to the index.js file, webpack start scanning all the dependencies (require / import) from the entry point file creates a dependency graph and generates a single output file specified in the output configuration  (bundle.js). Now all we need to do is reference the bundle.js file in the Applications startup page.

<script src="./dist/bundle.js"></script>

Below is the minimal webpack configuration required to bundle a React Application, notice that we specify the entry as index.js and the output as bundle.js

module.exports = {
  entry: './src/index.js',
  output: {
    filename: './dist/bundle.js'
  },
  module: {
    rules: [
      {
test: /\.(js|jsx)$/,
exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
};

Loaders
Loaders are used to configure webpack to process non Javascript/JSON file, React uses JSX syntax which webpack does not understand by default. To transform JSX and other types of content we need to configure the appropriate loader in webpack configuration.

In the above webpack configuration the test: /\.(js|jsx)$/ entry tells webpack to transform content from .js and .jsx files. The use: ['babel-loader'] entry tells webpack which loader should be used to transform the jsx content, in this case we will use the babel-loader to transform JSX content into JavaScript. 

Search Flipkart Products:
Flipkart.com

No comments: