Practical examples

12. Practical examples

In this lesson, we will explore real-world examples of projects using Turbopack, analyzing their benefits and challenges. These case studies will provide insights into how Turbopack can be leveraged in different scenarios and help you understand its practical applications.

Case Study 1: E-Commerce Website

Project Overview: An e-commerce website built with Turbopack to manage product listings, user accounts, and a shopping cart. The site handles a large volume of images and dynamic content.

Benefits:

  1. Performance: Turbopack’s fast build times and optimized bundling significantly improved the site’s performance, leading to faster page loads and a better user experience.
  2. Code Splitting: By using code splitting, the site loaded only the necessary JavaScript for each page, reducing the initial load time and improving performance for returning users.
  3. Image Optimization: Leveraging image-webpack-loader, the project saw a reduction in image file sizes without compromising quality, resulting in faster image loading times.

Challenges:

  1. Complex Configuration: Managing multiple entry points and configuring the build process for various environments required a deep understanding of Turbopack’s configuration options.
  2. Initial Learning Curve: The development team had to invest time in learning Turbopack and adjusting their workflow to integrate it effectively.

Configuration:

javascript
	const path = require('path');
	const HtmlWebpackPlugin = require('html-webpack-plugin');
	const { CleanWebpackPlugin } = require('clean-webpack-plugin');
	const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
	const MiniCssExtractPlugin = require('mini-css-extract-plugin');
	const Dotenv = require('dotenv-webpack');
	
	module.exports = {
	  mode: 'production',
	  entry: {
	    app: './src/index.js',
	    admin: './src/admin.js'
	  },
	  output: {
	    filename: '[name].[contenthash].js',
	    path: path.resolve(__dirname, 'dist'),
	    publicPath: '/'
	  },
	  module: {
	    rules: [
	      {
	        test: /\.js$/,
	        exclude: /node_modules/,
	        use: 'babel-loader'
	      },
	      {
	        test: /\.css$/,
	        use: [MiniCssExtractPlugin.loader, 'css-loader']
	      },
	      {
	        test: /\.(png|jpg|gif|svg)$/,
	        use: [
	          'file-loader',
	          {
	            loader: 'image-webpack-loader',
	            options: {
	              mozjpeg: {
	                progressive: true,
	                quality: 65
	              },
	              optipng: {
	                enabled: true
	              },
	              pngquant: {
	                quality: [0.65, 0.9],
	                speed: 4
	              },
	              gifsicle: {
	                interlaced: false
	              },
	              webp: {
	                quality: 75
	              }
	            }
	          }
	        ]
	      }
	    ]
	  },
	  optimization: {
	    usedExports: true,
	    minimizer: [
	      `...`, // Include the default minimizers (e.g., Terser for JS)
	      new CssMinimizerPlugin()
	    ],
	    splitChunks: {
	      chunks: 'all'
	    }
	  },
	  plugins: [
	    new CleanWebpackPlugin(),
	    new HtmlWebpackPlugin({
	      template: './src/index.html',
	      filename: 'index.html'
	    }),
	    new MiniCssExtractPlugin({
	      filename: '[name].[contenthash].css'
	    }),
	    new Dotenv({
	      path: './.env.production'
	    })
	  ]
	};
	
	// src/index.js
	import './styles.css';
	
	function component() {
	  const element = document.createElement('div');
	  element.innerHTML = 'Welcome to our e-commerce site!';
	  return element;
	}
	
	document.body.appendChild(component());

Case Study 2: News Portal

Project Overview: A news portal with frequent content updates and high traffic. The site required efficient handling of dynamic content and rapid deployment of new features.

Benefits:

  1. Hot Module Replacement (HMR): Enabled the development team to see changes in real-time without full page reloads, speeding up the development process.
  2. Tree Shaking: Reduced the bundle size by removing unused code, leading to faster load times.
  3. Environment Variables: Managed different configurations for development and production environments using dotenv-webpack.

Challenges:

  1. Dynamic Content Management: Handling frequent content updates and ensuring optimal performance was challenging.
  2. Scalability: As the site grew, maintaining build performance and managing dependencies became more complex.

Configuration:

javascript
	const path = require('path');
	const HtmlWebpackPlugin = require('html-webpack-plugin');
	const { CleanWebpackPlugin } = require('clean-webpack-plugin');
	const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
	const MiniCssExtractPlugin = require('mini-css-extract-plugin');
	const Dotenv = require('dotenv-webpack');
	
	module.exports = {
	  mode: 'production',
	  entry: './src/index.js',
	  output: {
	    filename: '[name].[contenthash].js',
	    path: path.resolve(__dirname, 'dist'),
	    publicPath: '/'
	  },
	  module: {
	    rules: [
	      {
	        test: /\.js$/,
	        exclude: /node_modules/,
	        use: 'babel-loader'
	      },
	      {
	        test: /\.css$/,
	        use: [MiniCssExtractPlugin.loader, 'css-loader']
	      },
	      {
	        test: /\.(png|jpg|gif|svg)$/,
	        use: [
	          'file-loader',
	          {
	            loader: 'image-webpack-loader',
	            options: {
	              mozjpeg: {
	                progressive: true,
	                quality: 65
	              },
	              optipng: {
	                enabled: true
	              },
	              pngquant: {
	                quality: [0.65, 0.9],
	                speed: 4
	              },
	              gifsicle: {
	                interlaced: false
	              },
	              webp: {
	                quality: 75
	              }
	            }
	          }
	        ]
	      }
	    ]
	  },
	  optimization: {
	    usedExports: true,
	    minimizer: [
	      `...`, // Include the default minimizers (e.g., Terser for JS)
	      new CssMinimizerPlugin()
	    ],
	    splitChunks: {
	      chunks: 'all'
	    }
	  },
	  plugins: [
	    new CleanWebpackPlugin(),
	    new HtmlWebpackPlugin({
	      template: './src/index.html',
	      filename: 'index.html'
	    }),
	    new MiniCssExtractPlugin({
	      filename: '[name].[contenthash].css'
	    }),
	    new Dotenv({
	      path: './.env.production'
	    })
	  ]
	};
	
	// src/index.js
	import './styles.css';
	
	function component() {
	  const element = document.createElement('div');
	  element.innerHTML = 'Latest News';
	  return element;
	}
	
	document.body.appendChild(component());
	
	// Enable Hot Module Replacement
	if (module.hot) {
	  module.hot.accept();
	}

Case Study 3: Portfolio Website

Project Overview: A personal portfolio website showcasing projects, blog posts, and contact information. The site needed to be fast and visually appealing.

Benefits:

  1. Minification: Reduced the size of JavaScript and CSS files, leading to faster load times.
  2. Clean Output: Used clean-webpack-plugin to ensure the output directory was always up-to-date, removing old files and preventing clutter.
  3. HTML Generation: Leveraged html-webpack-plugin to dynamically generate HTML files and inject bundled scripts, simplifying the deployment process.

Challenges:

  1. Initial Setup: Configuring the build process to handle various types of content (e.g., images, styles) required careful planning.
  2. Maintaining Performance: Ensuring that the site remained fast and responsive as new content was added.

Configuration:

javascript
	const path = require('path');
	const HtmlWebpackPlugin = require('html-webpack-plugin');
	const { CleanWebpackPlugin } = require('clean-webpack-plugin');
	const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
	const MiniCssExtractPlugin = require('mini-css-extract-plugin');
	const Dotenv = require('dotenv-webpack');
	
	module.exports = {
	  mode: 'production',
	  entry: './src/index.js',
	  output: {
	    filename: '[name].[contenthash].js',
	    path: path.resolve(__dirname, 'dist'),
	    publicPath: '/'
	  },
	  module: {
	    rules: [
	      {
	        test: /\.js$/,
	        exclude: /node_modules/,
	        use: 'babel-loader'
	      },
	      {
	        test: /\.css$/,
	        use: [MiniCssExtractPlugin.loader, 'css-loader']
	      },
	      {
	        test: /\.(png|jpg|gif|svg)$/,
	        use: [
	          'file-loader',
	          {
	            loader: 'image-webpack-loader',
	            options: {
	              mozjpeg: {
	                progressive: true,
	                quality: 65
	              },
	              optipng: {
	                enabled: true
	              },
	              pngquant: {
	                quality: [0.65, 0.9],
	                speed: 4
	              },
	              gifsicle: {
	                interlaced: false
	              },
	              webp: {
	                quality: 75
	              }
	            }
	          }
	        ]
	      }
	    ]
	  },
	  optimization: {
	    usedExports: true,
	    minimizer: [
	      `...`, // Include the default minimizers (e.g., Terser for JS)
	      new CssMinimizerPlugin()
	    ],
	    splitChunks: {
	      chunks: 'all'
	    }
	  },
	  plugins: [
	    new CleanWebpackPlugin(),
	    new HtmlWebpackPlugin({
	      template: './src/index.html',
	      filename: 'index.html'
	    }),
	    new MiniCssExtractPlugin({
	      filename: '[name].[contenthash].css'
	    }),
	    new Dotenv({
	      path: './.env.production'
	    })
	  ]
	};
	
	// src/index.js
	import './styles.css';
	
	function component() {
	  const element = document.createElement('div');
	  element.innerHTML = 'Welcome to my portfolio!';
	  return element;
	}
	
	document.body.appendChild(component());

Conclusion

These case studies demonstrate the versatility and power of Turbopack in various real-world scenarios. By leveraging Turbopack’s features and optimizations, these projects achieved significant improvements in performance, maintainability, and user experience.