TIL: Webpack Basics

Traversy Media Youtube tutorial

My Notes

  • webpack.config.js is commonjs:
const path = require('path')

module.exports = { 
.///
.///
}

Loaders

  • Loaders allow you to process other file types like sass
  • Test option/key takes regex that’s specifies the extension you want to apply the loader on
module: {
    rules: [
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
    ]
}
  • style-loader, css-loader, & sass-loader are installed as npm modules

Plug-ins

  • Plug-ins are a little more powerful than loaders
  • The one below, allows you to do some html templating as part of the build process, that file automatically imports relevant js, css, images etc
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

module: {
   plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack App',
      filename: 'index.html',
      template: 'src/template.html',
    }),
    new BundleAnalyzerPlugin(),
  ],
}

Caching

  • For caching, you can edit the output key to look like this
module.exports = {
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name][contenthash].js',
    clean: true,
  },
}
  • to elaborate on how this helps with caching performance, these sites are distributed as static html, javascript, & css, so, if the contents of a file change, the hash changes, meaning the file name changes, which then triggers a refresh of the cache.

Source map & console.log()

Quality of life item, definitely recommend

  • Just made sourcemap work on the profile dashboard. What this does is take the javascript files generated by webpack, and map the line of your console.logs() to the actual source code.
  • this is useful because code generated by webpack is always modified (either minified, or minified & extra lines added for the dev environment) - this means that the line number indicated in the browser won’t map to the line number of your console.log() in your IDE
module.exports = {
  devtool: 'source-map',
}

configuring dev server

= first npm install webpack-dev-server

  • then modify your webpack.config.js
module.exports = {
  devServer: {
      static: {
        directory: path.resolve(__dirname, 'dist'),
      },
      port: 3000,
      open: true,
      hot: true,
      compress: true,
      historyApiFallback: true,
    },
}

images

module.exports = {
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name][contenthash].js',
    clean: true,
    assetModuleFilename: '[name][ext]',
  },

    module: {
        rules: [
          {
            test: /\.(png|svg|jpg|jpeg|gif)$/i,
            type: 'asset/resource',
          },
        ]
    }
}

Full config

Find the full config on Brad’s Github