I am very new to next.js
. Using it for the server side rendering of my application.
According to the documentation you can import css files from a static folder which should be in root directory but i want to import css from node_modules because i have extended bootstrap and created my own package.
This is the solution you are probably looking for:
3 simple steps:
npm install --save @zeit/next-css
// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
})
import 'bootstrap-css-only/css/bootstrap.min.css';
Note: Using Next v 8+
Other solutions are workarounds from before next-css was available, but as shown above, there is a simple and supported solution now. It was provided by one of the core team members: https://spectrum.chat/next-js/general/ignoring-folders-files-specifically-fonts~4f68cfd5-d576-46b8-adc8-86e9d7ea0b1f
Use @webdeb/next-styles instead of @zeit/next-css.Then you can normally import any node module style.
const withStyles = require('@webdeb/next-styles')
module.exports = withStyles({
sass: true, // use .scss files
modules: true,
})
Since Nextjs 9.5.4, you can now import the css file directly from node_modules into the component where you need it (not required to be in _app.js). Just like this
import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
See docs here for more info - https://nextjs.org/docs/basic-features/built-in-css-support. All the best.
Since Next.js 9.2, there is no more need to use next-css
and withCSS
or withStyle
. Next.js natively handles CSS imports.
Since these may come with Webpack issues (see this issue: Having trouble importing CSS in NextJs), here's the way to configure loaders with webpack. In your terminal:
npm install file-loader --save-dev
npm install url-loader --save-dev
Then replace (or complete) your next.config.js
file with the following:
module.exports = {
cssModules: true,
webpack: (config, options) => {
config.node = {
fs: "empty",
};
config.module.rules.push({
use: [
options.defaultLoaders.babel,
{
loader: "url-loader?limit=100000",
},
{
loader: "file-loader",
},
],
});
return config;
},
};
Don't forget to remove any mention of withCSS
, withStyle
or next-css
since they may cause some errors to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With