Cant change page with 'next/link' & 'next-css'
standy opened this issue Β· 221 comments
This is bug report
Link does not work with css-module imported. That happens when page with Link has no css, and linked page has. No errors in console, so im not sure about reasons, but there is minimal repo to reproduce:
https://github.com/standy/next-css-error
Bug appears in next@7.0.0
+ next-css@1.0.1
,
Older next@6.1.2
+ next-css@0.2.0
works fine
I have the exact same issue, on the exact same versions as well.
Confirmed work around: make every page import some css.
Same problem except with next-css. Clicking links importing less just don't respond. My workaround was to stop using less/css. Note this ticket vercel/next.js#5264 (comment) suggests you can import blank in _app.js.
https://spectrum.chat/thread/2183fc55-236d-42cb-92b9-3ab10acc6303?m=MTUzODU2NDg2ODA2Mg==
Next team is aware and working on it! It's complex and will take time.
Importing an empty stylesheet into _app.js
nor importing a stylesheet on every page resolved the issue for me locally.
@kylemh I tried Importing an empty stylesheet into _app.js nor importing a stylesheet on every page resolved the issue for me locally.
but still not working
It's a strategy some have professed, but it doesn't resolve anything for me - just like you.
Same problem
I would fuckin' love to β€οΈ
@timneutkens The error is gone, great job! However when changing routes I'm not getting that new route's style... is anyone else having that issue?
Unfortunately I have to go and won't be able to troubleshoot it further or provide additional details today.
^ this precisely.
It doesn't look like I'm getting more CSS files per route - just on initial load.
SSR gets all styles properly.
Same issue with @zeit/next-css@canary not get css load on route change
That being said, I'd say this issue can be closed and another can be made on route-based code splitting withCSS with CSS Modules + PostCSS (at least for me) not working as desired?
Yes, on route change issue still present. Long time i used next6 with old next-css and regulary gets not loaded styles on route change. After refresh page it works as expected even on route change.
On 7 version it reproduced on every page change (not sometimes as next6).
But if you 1) load first page 2) transition to next page (gets not loaded styles) 3) refresh page - then you take working styles on both pages.
Looks like styles compilation is long process and delayed and page do not have time for take it and apply. After refresh page styles already precompiled and applied immediatelly.
my workaround this bug (on latest canary)
somewhere in _app.js
import Router from 'next/router';
Router.events.on('routeChangeComplete', () => {
if (process.env.NODE_ENV !== 'production') {
const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
const timestamp = new Date().valueOf();
els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
}
})
on every page reloads css after router change
my workaround this bug (on latest canary)
somewhere in
_app.js
... import Router from 'next/router'; ... Router.onRouteChangeComplete = () => { if (process.env.NODE_ENV !== 'production') { const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]'); const timestamp = new Date().valueOf(); els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp; } }
on every page reloads css after router change
look like bicyclecode
@plag thanks so much for sharing that! π
@plag I've updated your comment to use Router.events
instead: https://github.com/zeit/next.js#router-events
I had found a way to solve it. Not really perfect.
I have used a component Layout
in every page.
import React, { Component } from 'react';
import Head from 'next/head';
export default class Layout extends Component {
render() {
const { children, title, style, className } = this.props;
return (
<div className={'main-layout col ' + className} style={style}>
<Head>
<title>{title}</title>
{process.env.NODE_ENV !== 'production' && (
<link rel="stylesheet" type="text/css" href={'/_next/static/css/styles.chunk.css?v=' + Date.now()} />
)}
</Head>
<div className="main-content">{children}</div>
</div>
);
}
}
I had found a way to solve it. Not really perfect.
I have used a component
Layout
in every page.import React, { Component } from 'react'; import Head from 'next/head'; export default class Layout extends Component { render() { const { children, title, style, className } = this.props; return ( <div className={'main-layout col ' + className} style={style}> <Head> <title>{title}</title> {process.env.NODE_ENV !== 'production' && ( <link rel="stylesheet" type="text/css" href={'/_next/static/css/styles.chunk.css?v=' + Date.now()} /> )} </Head> <div className="main-content">{children}</div> </div> ); } }
How ur layout will work in _app.js
For example
<Container>
<Layout>
<Component>
</Layout>
</Container>
I had found a way to solve it. Not really perfect.
I have used a componentLayout
in every page.import React, { Component } from 'react'; import Head from 'next/head'; export default class Layout extends Component { render() { const { children, title, style, className } = this.props; return ( <div className={'main-layout col ' + className} style={style}> <Head> <title>{title}</title> {process.env.NODE_ENV !== 'production' && ( <link rel="stylesheet" type="text/css" href={'/_next/static/css/styles.chunk.css?v=' + Date.now()} /> )} </Head> <div className="main-content">{children}</div> </div> ); } }
How ur layout will work in _app.js
For example<Container> <Layout> <Component> </Layout> </Container>
I am not using Layout
in _app.js. Every single page has a container with Layout
.
e.g. :
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Layout from '../components/layout/Layout';
class FeedbackSuccess extends Component {
render() {
return <Layout title="ζδ½ζε">ζδ½ζε</Layout>;
}
}
export default connect()(FeedbackSuccess);
Same issue, anyone can resolve it?
@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file in static
catalog and import it in _app.jsx
@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file instatic
catalog and import it in_app.jsx
this doesnt work
@popugang well, it works for me ;)
@cherniavskii did you try following #282 (comment) ?
@stian-midlertidig no, I've resolved it by importing empty css file and it works
Sorry, I meant to cc @popugang π
@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file instatic
catalog and import it in_app.jsx
it doesn't work for me but i try to add router event in _app.js as plag mentioned and it works
@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file instatic
catalog and import it in_app.jsx
this doesnt work
Try #282 (comment), it works
@tuanhuu
While waiting for fix, the simplest workaround is to create empty css file instatic
catalog and import it in_app.jsx
This doesn't work me.
None of them is working for me too.
None of them is working for me too.
Hope solution will come out soon....
My current workaround is to import all of the .css
files used throughout my app in the _app.js
file.
The drawback is that I have stylesheets loaded that are mostly unused on the current page, and I cannot co-locate CSS imports in the module that uses those styles. But it avoids this bug π
@cheong12001 @cemsusal @Jero786 @popugang
I'm curious how many of you are using @font-face
in your stylesheets.
@kylemh I have @font-face in my style sheets with the following code:
@font-face { font-family: 'GothamBlack_TR'; src: url('/static/fonts/gotham/GothamBlack_TR.eot'); src: url('/static/fonts/gotham/GothamBlack_TR.eot') format('embedded-opentype'), url('/static/fonts/gotham/GothamBlack_TR.woff2') format('woff2'), url('/static/fonts/gotham/GothamBlack_TR.woff') format('woff'), url('/static/fonts/gotham/GothamBlack_TR.ttf') format('truetype'), url('/static/fonts/gotham/GothamBlack_TR.svg#GothamBlack_TR') format('svg'); }
Need more sample size to confirm that itβs somehow related, but this makes me π€
I'm curious how many of you are using @font-face in your stylesheets.
@kylemh Not in my case. Have no @font-face
and experiencing the same problems.
You can try to reproduce with this repo. Sorry no sample data, you have to create a project and a subproject and try to navigate to a subproject from a project page to reproduce the issue. No @font-face
used in this repo.
I also removed @font-face
from my css and tested it and the issue persists.
So much for that idea π
I read out there a workaround that seems like fix this problem, could you try guys if that works for you as well?
just add in their .eslintrc
...
"rules": {
...
"no-console": 1,
...
}
...
@Jero786 that isn't a fix, but it's just preventing the react error renderer showing up. You likely still have hash collisions and your website should appear sightly off (missing some - if not all - styles)
I'm facing the same issues and tried all the workarounds suggested above. It has fixed the error messages however it is not loading the components CSS. Here's my next.config.js
:
const withSass = require('@zeit/next-sass');
module.exports = withSass({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]",
},
webpack: (config, { dev }) => {
config.module.rules.push(
{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node-modules/,
enforce: 'pre',
options: {
emitWarning: true
}
},
{
test: /\.(config)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
}
},
{
test: /\.(png|ttf|eot|wtf|jpg|svg|gif)$/,
use: [
{
loader: 'url-loader',
options: {}
}
]
},
);
const StyleLintPlugin = require('stylelint-webpack-plugin');
config.plugins.push(
new StyleLintPlugin({
emitErrors: false,
quiet: false,
}),
);
return config;
}
});
My _app.js
:
import App, { Container } from 'next/app';
import Head from 'next/head';
import React, { Fragment } from 'react';
import '../style/global.scss';
import INITIAL_STATE from '../utils/initialState';
export default class MyApp extends App {
state = { appState: INITIAL_STATE }
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
handleUpdateAppState = (event, step) => {
const appState = { ...this.state.appState };
appState[step][event.target.name] = event.target.value;
this.setState({ appState });
}
handleUpdateCheckboxState = (checkboxObj, step) => {
const appState = { ...this.state.appState };
appState[step] = checkboxObj;
this.setState({ appState });
}
render() {
const { Component, pageProps } = this.props;
return (
<Fragment>
<Head>
{process.env.NODE_ENV !== 'production' && (
<link rel="stylesheet" type="text/css" href={`/_next/static/css/styles.chunk.css?v=${Date.now()}`} />
)}
</Head>
<Container>
<Component
onUpdateAppState={this.handleUpdateAppState}
onUpdateCheckboxState={this.handleUpdateCheckboxState}
appState={this.state.appState}
{...pageProps}
/>
</Container>
</Fragment>
);
}
}
global.scss
is not empty, it loads the vendors SCSS and some variables.- When I open
/_next/static/css/styles.chunk.css
the components CSS is there but the first time the components are rendered their CSS is not loaded.
I was able to prevent the error message by using these options in the withSass import:
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]",
},
The reason why the localIdentName
is just [local]
is because I'm not using hashes in the css class names and if I disable cssModules I get the 'Unhandled rejection' error
For me a slightly different version of the above worked as temporary fix.
I am using Less so I installed "@zeit/next-less": "^1.0.2-canary.2"
and then in _app.js
:
import Router from 'next/router'
Router.events.on('routeChangeComplete', () => {
const els = document.querySelectorAll('link[href*="/_next/static/chunks/styles.chunk.css"]')
const timestamp = new Date().valueOf()
els[0].href = '/_next/static/chunks/styles.chunk.css?v=' + timestamp
})
The difference with the above is that I used /_next/static/chunks/styles.chunk.css
instead of /_next/static/css/styles.chunk.css
I am using sass in my project and initially had the "Unexpected Rejection", however upgrading to "@zeit/next-sass": "^1.0.2-canary.2"
worked in removing the error. However, now I have the problem that my css wont load when switching pages, only after I refresh does it load. I have tried the solutions mentioned by @afuggini and @plag however I keep getting this error.
@farisT Make sure the path on your _app.js and the path on your page source code matches.
@samhenri this solution worked for me. Thank you very much! Also I did not need to install any canary builds to make it work. I just needed the 3 lines in the withSass config
Edit: It seems I was too quick with my testing. It only works on some pages :(
I just wanted to add that I'm also experiencing this issue beyond simply route changes: any time I render a component in the client that is different than what is rendered on the server, the component's CSS fails to load.
class Comp extends Component {
state = {
isMobile: false
};
componentDidMount() {
if (window && window.matchMedia("(max-width: 400px)").matches) {
this.setState({ isMobile: true });
}
}
render() {
// MobileComponent.scss is not working
return this.state.isMobile ? <MobileComponent /> : <DesktopComponent />
}
}
I assumed this was worth mentioning here as it feels related, but if I'm alone here or this is actually unrelated I am happy to open a new issue with all of the necessary details.
@chancestrickland Exactly the same here. I have at least one component that is not stateless and any state change unloads the CSS and then loads it again with the config that I've posted above. Since I have some transitions in the CSS it shows the default properties such as colors and borders transitioning to the properties I have set in my styles.
I had to move all SCSS imports to my global.scss and downgraded next and next-sass to the stable versions.
I created a Head component and included CDN urls to relevant stylesheets there as follows.
`import Head from 'next/head'
function Heading(props){
return (
<title>{props.title}</title>
)
}
export default Heading `
Then I used this heading whenever stylesheets are needs.This began working perfectly for me.
I basically spent the entire afternoon fighting this annoying bug and none of the solutions I found so far worked for me.
So I've managed to come up with another possible quick-and-dirty workaround, if you don't mind performing an automatic hard-reload whenever the error occurs.
Put this in your _app.js
:
if (process.env.NODE_ENV !== 'production') {
require('next/router').default.events.on('routeChangeError', (err, url) => {
if (err.stack.startsWith("TypeError: Cannot read property 'call' of undefined\n at __webpack_require__")) {
location.href = url;
}
});
}
I don't need the Router
anywhere else in my _app.js
, hence the require
statement; but you could also do:
import Router from 'next/router';
if (process.env.NODE_ENV !== 'production') {
Router.events.on('routeChangeError', (err, url) => {
if (err.stack.startsWith("TypeError: Cannot read property 'call' of undefined\n at __webpack_require__")) {
location.href = url;
}
});
}
I know it's stupid, but it works. Careful if you're not simply copy-pasting β there are 4 spaces between \n and "at webpack_require".
I didn't have much luck with the solutions posted above. The best results I got was from the solution @plag showed, but it didn't work reliably (it just didn't work on few of the pages).
What ended up fixing it for me was importing antd
like this import 'antd/dist/antd.css';
and not the modularised solution that's shown in the example (https://github.com/zeit/next.js/tree/canary/examples/with-ant-design)
Additionally, the styles we wrote are inside of 1 big .scss
file with bunch of imports. When this issue get's fixed we'll split up our styles per component.
Currently using html <a href="/"></a>
instead of Link or next-routes/Link π
That would make everything SSR, fwiw
Import some xx.css file in every page can reslove this problem
For me the only solution so far was to move all of the css imports to the _app
file, the other solutions either didn't work or brought up new issues for me, it's similar to what @DyslexicDcuk is doing but I'm not using scss
, didn't try the one proposed by @Sylvenas yet.
Also be sure to test the builds as well since sometimes I've seen that the issue was fixed by a solution on my local machine but when building the app the issue would still persist.
This has been killing me for a while now. I wrote the following hack to use until this gets fixed properly:
// HACK: Reload CSS in development
// Remove when this issue is resolved:
// https://github.com/zeit/next-plugins/issues/282
function initializeCssHack() {
if (process.env.NODE_ENV == 'production') return;
const href = '/_next/static/css/styles.chunk.css';
Router.events.on('routeChangeComplete', () => {
const css = document.querySelector(`link[href^="${href}"]`);
const newCss = css.cloneNode();
newCss.href = `${href}?c=${Date.now()}`;
newCss.onload = () => css.remove();
css.parentNode.appendChild(newCss);
});
}
I call this at the top level within _app.js
and am now able to successfully import CSS files within modules when running in development.
I'm brand new to Next and have been tearing my hair out for 3 days on this. I finally found this thread which was quite hard to find not knowing the exact search terms. I even put a post on StackOverflow and a post on Spectrum about this.
FWIW, I'm trying to migrate my nodejs/bootstrap/express app to Next and I came upon this by trying to load 3rd party React modules with their own CSS files. Therefore, I encountered this bug pretty early on in my exploration with Next. At least I see from all the comments that I'm not alone. π’
Update: for those of you who say the temporary fixes don't work, I had to combine a couple of the approaches above to achieve success. Each one alone didn't quite do it.
- Add an empty style.css in my Layout.js which is included in every single page of my app.
- Add the following to my _app.js
import Router from 'next/router';
Router.onRouteChangeComplete = () => {
if (process.env.NODE_ENV !== 'production') {
const els = document.querySelectorAll('link[href*="/_next/static/css/styles.chunk.css"]');
const timestamp = new Date().valueOf();
els[0].href = '/_next/static/css/styles.chunk.css?v=' + timestamp;
}
}
Importing an empty stylesheet into _app.js
worked for me, both with canary and with this version
i have the same problem.adding css files to a wrapper component solves the problem waiting for a proper fix
Updated all libraries and the problem is still happening. I've left the project I was working but I'll try to reproduce the problem in a personal project and post the link here. The only viable solutions were:
- Use global styles for vendor libraries and load them in the _app.js or in some sort of wrapper
- Use a CDN for global styles and resets
- Styled components for components
There's also a weird issue that on the first time you change routes, if there's any component using css animations, you can see the default browser styles changing to the styles that you created. Some times it happens whenever the component state has changed, if it is not a stateless component.
I can't resolve this problem even with any solutions posted above. Is it really necessary to deal with this during development? π
Solved with a mixture of above empty stylesheets, and building project once. Yay! ¬¬
I got it to work by adding an empty stylesheet to _app.js, using the onRouteChangeComplete
watcher and also adding an empty stylesheet to whichever page is crashing. I have to say that this is kind of hacky and I know in the future I may delete the empty stylesheet if I forget what it's for. Please update if a proper fix is found, thank you.
How about updating Next
to the new version 8.0.0
?
How about updating
Next
to the new version8.0.0
?
Same
How about updating
Next
to the new version8.0.0
?
Just the developers do not want to do anything about it. Broke in version 7 and forgot
Just the developers do not want to do anything about it. Broke in version 7 and forgot
I'm very aware of this issue, the thing is that it doesn't happen consistently and it's very hard to debug, the 70 comments and 50 π and no real solution being figured out are evidence of that.
I'll be focusing on fixing this soon, but it's not trivial and will probably take a significant amount of my time, hence why I haven't been able to look into it yet.
How about updating
Next
to the new version8.0.0
?
I don't have access to the same project that I had reported the issue because I left the company I was working but I've copied the configuration file and package.json, updated with next 8.0.0 and the problem still persists with SCSS. I wasn't able to reproduce the animation bug when the state changes but I believe this has more to do with the transition
property being loaded before the component styles than with next, unless something is making the component unmount/mount again instead of updating. In case someone ends up with the same problem, just make sure that you're not using transition: all time animation-type
in any kind of "global" class
It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.
If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this? As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?
Does that make any sense?
If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this?
This wouldn't be the correct solution to the issue.
As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?
On-demand entries has been a part of Next.js since 3.x
It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.
The main issue here is that webpack doesn't handle dynamically loaded styles correctly / the HMR part of the extraction plugin seems to work incorrectly. Another issue is that it expects a file to load that is never loaded.
It seems to me that the loading fails because the server does not have the page prebuilt (builds it on request), at least in my case, only the initial page load is the issue... Once you refresh the browser, you can go to previous page and back to the problematic page with no issues via next/link.
If that is the case, is there any way I can try to run next in dev mode that would behave more like the production build and hopefully resolve this? As far as I remember, there were some major dev performance optimizations in the version that introduced this bug, and I have a feeling its because this building happens on demand?
Does that make any sense?
I have experienced this but also have experienced constant failures - it's very strange.
This is just slightly frustrating because something I have used previously that works fine, that you assume is core to the framework is now broken and not working properly and is the same across multiple versions of the package. I lost hours thinking I was doing something wrong myself.
But as the developer says I believe this would be a complex issue to fix - we can solve this together with further debugging. I will try my best to help.
We cannot help because we do not know how the kernel works. Researching his work will take too long. I think because of the change in version 7 https://nextjs.org/blog/next-7/#css-imports
Does updating next to 8.0.3 fix it, or it has nothing to do with this?
I'm not sure about other peoples' situations, but client-side routing works w/o error after upgrading to v8. I haven't dived into whether or not route-based style-splitting is working correctly.
Does updating next to 8.0.3 fix it, or it has nothing to do with this?
dont fixed
I experience a similar behavior:
I have a page that loads react-table
stylesheet with
import 'react-table/react-table.css';
I have another page "no-style" that doesn't load any CSS.
And finally, I have a link that targets a 404.
So that's 3 links in my menu:
- react-table
- no-style
- 404
At initial load, I can navigate from "react-table" to "no-style" and back to "react-table".
As soon as I hit the "404" page, I cannot go back to "react-table" but I can go to "no-style".
From there, opening a private browser session, restarting the dev server, closing and reopening the browser tab... None of them will make the link to "react-table" work again.
The only solution from there is to manually write the URL to the "react-table" page and it will be working again until I hit the "404" and everything is back to broken.
I will give the above workarounds a try.
I'm on 8.0.3.
The problem is present in prod and dev mode.
Edit:
Loading an empty CSS file in my _app.js
fixed it.
import '../static/dummy.css';
Try new plugins versions with canary4
@zeit/next-css@0.2.1-canary.4
has the same problem.
I don't even seem to be able to reach my "react-table" page anymore without manually typing the URL first.
Just the developers do not want to do anything about it. Broke in version 7 and forgot
I'm very aware of this issue, the thing is that it doesn't happen consistently and it's very hard to debug, the 70 comments and 50 π and no real solution being figured out are evidence of that.
I'll be focusing on fixing this soon, but it's not trivial and will probably take a significant amount of my time, hence why I haven't been able to look into it yet.
@timneutkens
That's good to know, and by the way, I use "antd" through next-css, and it failed to switch to any page containing antd component through client navigation each and every time, 100% reproduceable! I am using "next": "^7.0.2" & "@zeit/next-css": "^1.0.1"
So if you need, I can create a demo for you.
They're aware of the issue, and are working on it.
@yxwu i made this basic example with the same problem
@ivanhuay In fact, I don't know if it's the same as this issue, but I've studied the issues you're talking about.
I had the same problem, and I found the answer over the course of a few days.
The first problem is with "with-css".
"With-css" has "css-loader-config", where optimize config is used.
if (!isServer) {
config.optimization.splitChunks.cacheGroups.styles = {
name: 'styles',
test: new RegExp(`\\.+(${[...fileExtensions].join('|')})$`),
chunks: 'all',
enforce: true
}
}
This config ends up making all css a single chunk file.
I removed this config from "next.config.js" to fix the problem.
if (!isServer) {
delete optimization.splitChunks.cacheGroups.styles;
}
And also changed the MiniCssExtractPlugin setting.
plugins.forEach((plugin, index) => {
if (plugin.constructor.name === 'MiniCssExtractPlugin') {
plugins[index] = new MiniCssExtractPlugin({
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
});
}
});
Let me know if you have any other ideas.
@kimorkim this solution doesn't work with Link from 'next/link'
i uploaded a new version in other branch
https://github.com/ivanhuay/next-css-conflict-example/tree/custom_config
@ivanhuay
oh, i see.
But it's not what it used to be.
To explain in detail, with-css makes all the styles used into a single chunk file.
So you cannot use a classname of the same name.
This can be resolved simply by using the cssmodule.
This file is automatically added to the "_document" and provided to the user.
However, it does not seem to update the already created "_document" when using "next/link".
This seems to be because "nextjs" operates as "spa" after page loading.
Perhaps the perfect solution should be devised to update the "_document".
@ivanhuay
I've made a solution with your repository.
I didn't use cssmodule and with-sass.
https://github.com/kimorkim/next-css-conflict-example
By default, we used the configuration of scss directly and put the results into jsx.
next.config.js
module.exports = {
webpack(config, options) {
const { module } = config;
const { rules } = module;
rules.push({
test: /\.(sc|sa|c)ss$/,
use: ["css-loader", "sass-loader"]
});
return config;
}
};
index.jsx
import css from "./index.scss";
import Link from "next/link";
const Index = () => (
<div className="container">
<style>{css.toString()}</style>
<h1>index</h1>
<Link href="/b">
<a>a pagina b</a>
</Link>
</div>
);
export default Index;
I don't think it's a good way, but you can get the results you want.
@kimorkim that work for me thanks!
but the way that next-css works is correct?
i don't know if this is a bug or the expected behavior.
in any way it should be documented
@ivanhuay It is not the way to use "with-css".
It is a combination of ordinary webpack and css.
would be better to use the cssmodule when using nextjs.
This is the official way.
But I don't think there will be a problem with that.
Of course, it may differ from the optimization direction that nextjs is pursuing.
I need a better idea.
@kimorkim Thanks so much for your code in this comment
I've been battling the call undefined moduleid issue for a few days now, switching the versions of nearly everything and up until the point of dropping the nextjs dependency entirely and rolling our own SSR.
Thanks for figuring out a bandaid to get our build system working for another few weeks until something else introduces a breaking change!
so in "next": "^8.0.3", it's still the same, router.push is broken
I am having the same issue I think. Unable to navigate using Link tags unless I import styles used in subsequent linked pages. Is this related?
@kimorkim , I did in next.config.js how you wrote. In _document.js did import styles from bootstrap, tryed scss file import bootstrapStyles from "bootstrap/scss/bootstrap.scss";
and css file import bootstrapStyles from "bootstrap/dist/css/bootstrap.min.css";
, pasted <style dangerouslySetInnerHTML={{ __html: bootstrapStyles,}} />
in Head component, but in browser I recived <style>[object Object]</style>
. If I doing <style dangerouslySetInnerHTML={{ __html: JSON.stringify(bootstrapStyles) }} />
in browser I see <style>{}</style>
, just empty object ( Help me, please.
I have this problem, too. Importing an empty css file in _app.js half-resolved the problem for me. It allowed navigating to the next page to work, but the css imported in the next page wasn't actually applied.
Moving all css imports to _app.js fully resolved the problem. So, that seems to be the workaround that actually works.
@mrrotberry Even the same style import has different results depending on the webpack setting.
import css from "./index.scss";
//...
<style>{css.toString()}</style>
//...
My setting must be use css.toString()
.
The bootstrapStyles
you used will be able to check the contents with the console.
Check your console.log
@popuguytheparrot Thanks for the help! I was able to fix it by adding the following to my _document.js
:
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
export default class CustomDocument extends Document {
static async getInitialProps(ctx) {
return {};
}
render() {
return (
<html lang="en">
<Head>
{process.env.NODE_ENV == 'production' && (
<link
rel="stylesheet"
type="text/css"
href={'/_next/static/css/styles.chunk.css?v=' + Date.now()}
/>
)}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
My export command has to specify NODE_ENV
to work:
NODE_ENV=production && rm -rf out && next build && next export
More notes on this...
You have to manually hit the dev server to create /_next/static/css/styles.chunk.css
. This really threw me, because it broke in my CI pipeline. The CI pipeline isn't hitting the dev server... so it never creates the styles.chunk.css
file.
I've temporarily turned off my CI pipeline so that I can manually create styles.chunk.css
using the dev server and deploy manually.
I was able to solve the problem π«. Check solution here: https://github.com/shashkovdanil/next-styles-fixed. Works in dev and prod. I extracted the next-css
packages for work with .sss
files (SugarSS), you can not do it.
Most likely fix in the update next
and @zeit/next-css
packages.