Next.js: How to include CSS from node_modules in project?

Created on 12 Jan 2020  Â·  27Comments  Â·  Source: vercel/next.js

I am trying to

import 'bootstrap/dist/css/bootstrap.min.css';

in my next.js project but I get following error

Module parse failed: Unexpected token (6:3) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

I have next.config.js file in root directory of project. It has this configuration

// next.config.js 
const withCSS = require('@zeit/next-css');

module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  }
});

I followed this comment which apparentlyworks but not for me. Any ideas why?

Most helpful comment

Sorry, yeah — that read more link will work soon.
Here's the resolved version which gives instructions on how to fix "Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to pages/_app.js.":
https://github.com/zeit/next.js/blob/canary/errors/css-global.md

@timer I've been seeing this issue pop up lately with all the new changes in 9.x, There are a lot of third party packages that ask us to import their .css files from the node_modules folder. Do you see next.js adding support for this any time soon? I feel like the _app.js is having to add all these .css files directly, I'll have eventually like 10 different CSS files from all these different packages that I have to load globally when I'm only trying to load them when the specific component is being used. I would love to know if there's already a solution for this or any recommendations would be greatly appreciated!

All 27 comments

Delete your next.config.js, upgrade to next@canary, and try again! It should work with zero configuration.

I upgraded and now I get this. Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.

This is whole message

./node_modules/bootstrap/dist/css/bootstrap.css
Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.
Read more: https://err.sh/next.js/css-global
Location: pages/index.js

UPDATE
I managed to make it work with next.config.js. It worked with this configuration

// next.config.js 
const withCSS = require('@zeit/next-css');

module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  }
});

it is same one that didn't work 30 minutes ago. I had to restart PC for it to work. Looks like it was problem on my side.
But I am wondering. Why can't I load CSS without it?

The error you saw was because you needed to move that CSS import to the _app.js file.

You'd need to create a pages/_app.js file (docs). And then import any/all CSS files you want in that file.

So pages/_app.js would be something like...

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css';
import 'any-other-css-you-want.css';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Here is the help article that is linked in that error.

I understand now. Thank you so much for clarifying this to me.

Sorry, yeah — that read more link will work soon.
Here's the resolved version which gives instructions on how to fix "Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to pages/_app.js.":
https://github.com/zeit/next.js/blob/canary/errors/css-global.md

Do note, @zeit/next-css is deprecated / legacy and is not recommended to be used anymore.

Oh well. Thanks for the heads up. This is usefull information. I will immediately use method you guys wrote. Thank you :)

[ error ] ./node_modules/react-datepicker/dist/react-datepicker.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .react-datepicker-popper[data-placement^="bottom"] .react-datepicker__triangle, .react-datepicker-popper[data-placement^="top"] .react-datepicker__triangle, .react-datepicker__year-read-view--down-arrow,
| .react-datepicker__month-read-view--down-arrow,
[ error ] ./node_modules/@fortawesome/fontawesome-svg-core/styles.css 1:8
Module parse failed: Unexpected token (1:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> svg:not(:root).svg-inline--fa {
|   overflow: visible; }
|

@muhaimincs I guess what @Timer meant by removing next.config.js is if you don't have any other webpack configs or environment variables in there. Since the example was just a simple next-css setup it made sense.

However to use @fortawesome in this case you need to have a loader set for that.

Working example for this would be, and append webpack to your module.exports

```
webpack: config => {
config.module.rules.push({
test: /.svg$/,
use: ['string-loader'],
});
return config
};

Sorry, yeah — that read more link will work soon.
Here's the resolved version which gives instructions on how to fix "Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to pages/_app.js.":
https://github.com/zeit/next.js/blob/canary/errors/css-global.md

@timer I've been seeing this issue pop up lately with all the new changes in 9.x, There are a lot of third party packages that ask us to import their .css files from the node_modules folder. Do you see next.js adding support for this any time soon? I feel like the _app.js is having to add all these .css files directly, I'll have eventually like 10 different CSS files from all these different packages that I have to load globally when I'm only trying to load them when the specific component is being used. I would love to know if there's already a solution for this or any recommendations would be greatly appreciated!

Sorry, yeah — that read more link will work soon.
Here's the resolved version which gives instructions on how to fix "Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to pages/_app.js.":
https://github.com/zeit/next.js/blob/canary/errors/css-global.md

@Timer I've been seeing this issue pop up lately with all the new changes in 9.x, There are a lot of third party packages that ask us to import their .css files from the node_modules folder. Do you see next.js adding support for this any time soon? I feel like the _app.js is having to add all these .css files directly, I'll have eventually like 10 different CSS files from all these different packages that I have to load globally when I'm only trying to load them when the specific component is being used. I would love to know if there's already a solution for this or any recommendations would be greatly appreciated!

any updates?
Seems like 9.2 and 9.3 is not usable till they fix all the css errors

+1 — this error also crops up when trying to implement styled-components: https://github.com/zeit/next.js/tree/canary/examples/with-styled-components

[ETA: I'd be happy to help contrib a fix if pointed in the right direction :]

thanks @M1ck0 it works! I doesn't work sadly!

wont the size of _app.js will be heavy if we have to import tons of third party libraries css from node_modules? Is there any other solution for this?

Well. If you are using tons of libraries for UI there _app is going to be heavy. Solution would be to import CSS files in components/pages that need them and not in _app, but I am not sure that this is possible.

@Tushant so true, this is why we need this solved

@M1ck0 I don't think so. Because when building it throws an error saying Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to src/pages/_app.js.

As I said.. It is not possible now but it might be solution if implemented.. not sure..

so what's the solution to be implemented?

Same problem with me! Only with the import of css in my package of components.

Anyone have a workaround for this? To use a library like full calendar it exports its own css.

Anyone have a workaround for this? To use a library like full calendar it exports its own css.

I got here! https://github.com/vercel/next.js/blob/master/errors/css-npm.md I didn't find an alternative solution and ended up removing the css import pro user in the application

best option I found was to use the postinstall hook and run a node script that copies the css files out of the node_modules into my public dir, then load those files with a link tag.

<link rel="stylesheet" href="/vendor/quill.snow.css" />
<link rel="stylesheet" href="/vendor/react-datepicker.css" />

makes sense to only load these files on the relevant pages.

postinstall hook

can you please let me know what is postinstall hook or can you show me some example for this

it's an npm hook., after the install command is finished the post install is executed.

package.json

  ...
  "scripts": {
    "dev": "node server",
    "build": "next build",
    "start": "cross-env NODE_ENV=production node server",
    "start:build": "cross-env NODE_ENV=production forever server &",
    "postinstall": "node ./scripts/copy_assets_to_public.js"     <-----
  },
  ...

copy_assets_to_public.js

const fs = require('fs');
const path = require('path');

const output_dir = '../public/vendor/';
const assets = [
  '../node_modules/react-datepicker/dist/react-datepicker.css',
  '../node_modules/react-quill/dist/quill.snow.css',
];

assets.forEach((asset_path) => {
  const filename = path.basename(asset_path);
  fs.createReadStream(path.resolve(__dirname, asset_path)).pipe(
    fs.createWriteStream(path.resolve(__dirname, output_dir, filename))
  );
});

Duplicate of https://github.com/vercel/next.js/issues/12079, please move all correspondence there!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jesselee34 picture jesselee34  Â·  3Comments

formula349 picture formula349  Â·  3Comments

renatorib picture renatorib  Â·  3Comments

rauchg picture rauchg  Â·  3Comments

swrdfish picture swrdfish  Â·  3Comments