Using reactstrap with Next.js

gsapienza picture gsapienza · Apr 24, 2018 · Viewed 19.2k times · Source

I am creating a React app using Next.js and am trying to use components provided by reactstrap.

The issue I seem to be running into seems to involve importing the CSS file named bootstrap/dist/css/bootstrap.min.css as the reactstrap guide says to do.

The error I am seeing is Error in bootstrap/dist/css/bootstrap.min.css Module parse failed: Unexpected token (6:3) You may need an appropriate loader to handle this file type.

Does anyone know what I have to do to make this work correctly? I am a new web developer so sorry if I am missing anything obvious.

Thanks!

Answer

mtl picture mtl · Apr 24, 2018

EDIT: As of Next.js 7, all you have to do to support importing .css files is to register the withCSS plugin in your next.config.js. Start by installing the plugin:

npm install --save @zeit/next-css

Then create the next.config.js file in your project root and add the following to it:

// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({/* my next config */})

You can test that this is working by creating a simple page and importing some CSS. Start by creating a CSS file:

// ./index.css
div {
    color: tomato;
}

Then create the pages folder with an index.js file. Then you can do stuff like this in your components:

// ./pages/index.js
import "../index.css"
export default () => <div>Welcome to next.js 7!</div>

You can also use CSS modules with a few lines of config. For more on this check out the documentation on nextjs.org/docs/#css.


Next.js < version 7

Next.js doesn't come with CSS imports by default. You'll have to use a webpack loader. You can read about how this works here: https://zeit.co/blog/next5#css,-less,-sass,-scss-and-css-modules.

Next.js also has plugins for CSS, SASS and SCSS. Here is the plugin for CSS: https://github.com/zeit/next-plugins/tree/master/packages/next-css. The documentation for that plugin makes it fairly simple:

  1. You create the _document file in pages/.
  2. You create the next.config.js file in the root.

Using the code snippets from the documentation should set you up to import CSS files.

You'll need at least version 5.0. You can make sure you have the latest Next.js installed: npm i next@latest.