Optimization Techniques

Optimization Techniques

Optimizing your application is crucial for ensuring it performs well in production. In this lesson, we will cover several optimization techniques that can be applied in Turbopack to improve your application’s performance. These techniques include tree shaking, minification, and caching.

Tree Shaking

Tree shaking is a process that eliminates dead code from your JavaScript bundle. It relies on the static structure of ES6 modules to detect and remove unused code, reducing the bundle size.

  1. Enable Tree Shaking: Ensure your code uses ES6 module syntax (import and export) and configure Turbopack to enable tree shaking.

    javascript
    	module.exports = {
    	  mode: 'production', // Set mode to 'production' to enable optimizations
    	  entry: './src/index.js',
    	  output: {
    	    filename: 'bundle.js',
    	    path: path.resolve(__dirname, 'dist')
    	  },
    	  optimization: {
    	    usedExports: true // Enable tree shaking
    	  }
    	};
    • mode: 'production': Enables production optimizations, including tree shaking.
    • usedExports: true: Marks unused exports for removal.

Minification

Minification reduces the size of your JavaScript and CSS files by removing whitespace, comments, and other unnecessary characters. This results in smaller file sizes and faster load times.

  1. JavaScript Minification: Turbopack uses Terser to minify JavaScript by default in production mode.

    javascript
    	module.exports = {
    	  mode: 'production' // Automatically minifies code in production mode
    	};
  2. CSS Minification: Use css-minimizer-webpack-plugin to minify CSS files.

    javascript
    	const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
    	
    	module.exports = {
    	  mode: 'production',
    	  entry: './src/index.js',
    	  output: {
    	    filename: 'bundle.js',
    	    path: path.resolve(__dirname, 'dist')
    	  },
    	  optimization: {
    	    minimizer: [
    	      `...`, // Include the default minimizers (e.g., Terser)
    	      new CssMinimizerPlugin()
    	    ]
    	  }
    	};

Caching

Caching helps improve the performance of your application by storing assets in the browser’s cache and reducing the number of network requests.

  1. Output Filenames with Hashing: Use content hashes in filenames to ensure that updated files are fetched by the browser while unchanged files are loaded from the cache.

    javascript
    	module.exports = {
    	  mode: 'production',
    	  entry: './src/index.js',
    	  output: {
    	    filename: '[name].[contenthash].js',
    	    path: path.resolve(__dirname, 'dist')
    	  }
    	};
    • [contenthash]: Generates a unique hash based on the content of the file.
  2. Cache-Control Headers: Configure your web server to set appropriate cache-control headers for your assets.

    apache
    	# Apache example
    	<FilesMatch "\.(js|css|html|png)$">
    	  Header set Cache-Control "max-age=31536000, public"
    	</FilesMatch>
    nginx
    	# Nginx example
    	location ~* \.(js|css|html|png)$ {
    	  expires 1y;
    	  add_header Cache-Control "public, max-age=31536000";
    	}

Example: Comprehensive Optimization Configuration

Here’s an example of a comprehensive configuration that includes tree shaking, minification, and caching:

javascript
	const path = require('path');
	const HtmlWebpackPlugin = require('html-webpack-plugin');
	const { CleanWebpackPlugin } = require('clean-webpack-plugin');
	const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
	
	module.exports = {
	  mode: 'production',
	  entry: {
	    app: './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: ['style-loader', 'css-loader']
	      }
	    ]
	  },
	  optimization: {
	    usedExports: true,
	    minimizer: [
	      `...`, // Include the default minimizers (e.g., Terser)
	      new CssMinimizerPlugin()
	    ],
	    splitChunks: {
	      chunks: 'all'
	    }
	  },
	  plugins: [
	    new CleanWebpackPlugin(),
	    new HtmlWebpackPlugin({
	      template: './src/index.html',
	      filename: 'index.html'
	    })
	  ]
	};
	
	// src/index.js
	import './styles.css';
	
	function component() {
	  const element = document.createElement('div');
	  element.innerHTML = 'Hello, Turbopack!';
	  return element;
	}
	
	document.body.appendChild(component());
  • Tree Shaking:

    • usedExports: true: Enables tree shaking to remove unused code.
  • Minification:

    • mode: 'production': Automatically enables JavaScript minification.
    • CssMinimizerPlugin: Minifies CSS files.
  • Caching:

    • [name].[contenthash].js: Uses content hashes in filenames to support caching.

This configuration ensures that your application is optimized for production, resulting in smaller bundle sizes, faster load times, and efficient caching.