问题
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!
回答1:
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:
- You create the
_document
file inpages/
. - 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
.
回答2:
If you are still getting the error:
Unexpected token (6:3) You may need an appropriate loader to handle this file type.
try this in your next.config.js:
// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
})
- Now you should be able to import styleshets from node_modules like this:
import 'bootstrap-css-only/css/bootstrap.min.css';
Note: Using Next v 8+
Background: I spent a few hours trying to simply import a CSS installed as a node_module and the various solutions are mostly hacky workarounds, but as shown above, there is a simple solution.
It was provided by one of the core team members
来源:https://stackoverflow.com/questions/49992423/using-reactstrap-with-next-js