How to add webpack loader to Next.js application

In this article, I will show how to add custom loader to your Next.js application. To simplify the example, I'll start with brand new application & just add some extension to be loaded as plain string.

Application set up

We start by creating a brand new next.js application. As stated in the documentation we run npx create-next-app and just add the name to it

$ npx create-next-app webpack-next

cd webpack-next
npm run dev

The resulting application looks like:
Alt Text

Changing the wepback configuration

Next.js abstracts away from us the webpack configuration. They leave a way to tweak it in our project, but it's less straightforward than editing webpack.config.js direct. As you see in the documentation:

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Important: return the modified config
    return config
  },
}

you have many ways of mess it up - for example by not returning the config as the framework require us to do.

Note! Every time you change next.config.js you are supposed to restart the dev sever manually. I'm suspicious of auto restarts, so even if it were restarting on it's own, as NuxtJS does, I would restart manually from time to time anyway.

The configuration where we specify the .my-files to be loaded as text:

module.exports = {
  reactStrictMode: true, // was there by default
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.module.rules.push({
      test: /\.my-file$/i,
      loader: "raw-loader",
    });

    // Important: return the modified config
    return config;
  },
};

We need to make sure to push to config.module.rules. Otherwise, if we were overriding the whole array, would drop all loaders specified by Next.js.

When we add an example files, /pages/test.my-file:

Test content

and import it in our js like this:

import test from "./test.my-file";

export default function Home() {
  return <div>{test}</div>;
}

the attempt to build will fail. That's because we have to install raw-loader first:

The resulting application:
Alt Text

Links

Summary

Here we have seen how to add custom loader to the Next.js application. If you want to see the repository, you can find it here:

GitHub logo marcin-wosinek / webpack-next

Example project with webpack 5 & next.js 11

If you want too see my other webpack related content:

21