next.js: Error resolving a CSS file import with custom Webpack rule

Hi!

I’m (eventually) attempting to build a PostCSS/cssnext setup on top of Next.js, but somehow importing a CSS file cannot be resolved.

My pages/index.js file tries to import the pages/index.css file (that exists):

import './index.css'

With the Webpack config:

next.config.js:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.css$/,
      exclude: /node_modules/,
      loader: ['style-loader', 'css-loader']
    });
    return config;
  }
};

results in

output:

yarn run v0.15.1
$ next
> Using "webpack" config function defined in next.config.js.
 DONE  Compiled successfully in 3004ms

> Ready on http://localhost:3000
{ Error: Cannot find module './index.css'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/kpuputti/code/projects/nextlatest/pages/index.js?entry:3:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3) code: 'MODULE_NOT_FOUND' }

Package versions in package.json:

  "dependencies": {
    "css-loader": "^0.26.1",
    "next": "2.0.0-beta.12",
    "style-loader": "^0.13.1"
  }

Do I need to do some extra setup to get the resolving work, or how should I approach this? Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 13
  • Comments: 15 (8 by maintainers)

Most upvoted comments

It seems like the problem is an imparity between server and client side rendering. You add a webpack loader for some new file type but it doesn’t apply on the first render (because SSR doesn’t involve bundling via webpack, right?), so it doesn’t work. But if you manage to re-render on the client (either by following a link or triggering HMR) it works.

If this is correct, the whole extending your webpack config to add additional loaders use case is flawed, because SSR is at the core of Next.js. @rauchg

The alternative is to rely on Babel transforms instead of webpack loaders, because those get applied consistently.

This is actually a duplicate of #544. Closing this in favor of having the full CSS importing discussion there.

@noeljackson That should be something interesting. I’d like to play with this.

I have the same problems when I import the bootstrap css. Is there any solution?