Search code examples
csswebpacksassnext.jswebpack-style-loader

Css not loading in production mode when using nextjs


Problem

When building and starting a production build of our application, no css is loaded. CHecking the devtools, I can see a myriad of errors and warnings:

Screenshot of errors and warnings in the console

Possible Culprits

I do not experience any of these problems, when starting the app in dev mode. Also, other assets like images or fonts are loaded correctly. We use scss and import the global stylesheet in _app.tsx like this:

import "../styles/globals.scss";

In order to solve a problem with another library, we had to setup a custom webpack config:

module.exports = phase => ({
  webpack: (config, { isServer }) => {
    config.module.rules.push({
      test: /\.node$/,
      use: "node-loader"
    });

    config.module.rules.push({
      test: /\.(ts|js)x?$/,
      use: [
        {
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            experimentalWatchApi: true,
            onlyCompileBundledFiles: true
          }
        }
      ],
      include: [path.resolve(__dirname, "node_modules/@private/")],
      exclude: [path.resolve(__dirname, "node_modules/@private/src/styleguide")]
    });

    if (!isServer) {
      config.module.rules.push({
        test: /\.s?[ac]ss$/i,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" },
          {
            loader: "resolve-url-loader",
            options: { removeCR: true, debug: true }
          },
          { loader: "sass-loader" }
        ]
      });
    }

    config.module.rules.push({
      test: /\.(png|jpe?g|gif)$/i,
      use: [
        {
          loader: "file-loader",
          options: {
            name: "[name].[ext]",
            exclude: /node_modules/
          }
        }
      ],
      exclude: [path.resolve(__dirname, "node_modules/@private/src")]
    });

    return config;
  }
});

Also, we this is the file of the custom server we use to start the application in production mode:

const PORT = parseInt(process.env.PORT, 10) || 3364;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("*", (req, res) => handle(req, res));

  server.listen(PORT, err => {
    if (err) throw err;
    console.log(`🐎 => Ready on http://localhost:${PORT}`);
  });
});

Assumptions

As the custom server is the only difference between production and development, I can only assume that the error is maybe somewhere there. But it looks fine to me. So if anybody has a hint or an idea, I would be very grateful.


Solution

  • Ok, I just deleted the .next folder prior to building the production version via npm run build and after that, everything worked. Seems like there is some problems with the chunk generation when the .next folder is there.