Let us talk about a minimal configuration for Webpack that can get us started with development with React.
A few basics first, why should we need Webpack as a build tool? :
- We need to transpile the JSX & React specific syntaxes.
- We need to transpile the ES6 code that we commonly use like spread operators.
- We need to have code-splitting & chunking so that we can have on-demand loading for our code bundles & we can optimize their sizes.
- We need a build system to generate the distributable, uglified, minified, compressed, transpiled & transformed code, that works continuously, watching the file changes.
Now that we know, for improved developer productivity, code churns need to be produced continuously & seamlessly through a build system, let us try writing our Webpack config.
A. Writing Webpack config
You may choose to keep this file at the root level of your project.
Lets double click on the sections that we added to our Webpack config.
This is the entry point of your react app. Usually, this is the file where you render the root component of your react application.
This configuration specifies where should we generate the bundles & output of the Webpack run.
We can switch between ‘development’ & ‘production’. We choose ‘development’ to see source maps & debug better.
Module: Here we specify how Webpack should load the files that it encounters as it starts recursively traversing the files starting from the entry point we specified.
We are using babel-loader to transpile our React (js & jsx) code along with two presets:
a. preset-react: This is to tell Webpack that it should use react specific babel settings to transpile our code.
We are also using two loaders for adding styles to our bundles:
a. css-loader: This is to allow Webpack to read files through CSS file imports.
b. style-loader: This allows Webpack to add style tags & insert styles into our bundles.
Optimization: Here we are specifying that Webpack should use UglifyJSPlugin to minify our bundles.
Plugins: This is where you can have post-processing on bundles like we are copying some view files to the distribution folder & generating source maps for the bundle.
B. Running Webpack
For running Webpack & requiring all the dependencies our package.json (at same folder level as webpack.config.js) should look like this:
Here we define two scripts, “build” & “build-watch”, to run Webpack picking our config.
Go to terminal & run:
npm run build-watch
This produces the bundles under the dist folder & also watches for file changes & keeps producing bundles as you save changes.
Now you need to point to the generated bundles from your view files.
You can also check out: https://github.com/gauravbehere/react-webpack-starter. I have added all the above boilerplate code in this repo.