javascript Next.js - 导入 css 文件不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50149729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Next.js - import css file does not work
提问by ArgenBarbie
I am creating a project with react, redux and next.js, and want to import CSS files in js.
我正在创建一个带有 react、redux 和 next.js 的项目,并且想在 js 中导入 CSS 文件。
I followed instructions in next.js/#cssand next-css, but find out that CSS styles do not work.
我按照next.js/#css和next-css 中的说明进行操作,但发现 CSS 样式不起作用。
My code is as follow:
我的代码如下:
pages/index.js:
页面/index.js:
import React from 'react'
import "../style.css"
class Index extends React.Component {
render() {
return (
<div className="example">Hello World!</div>
);
}
}
export default Index
next.config.js:
下一个.config.js:
const withCSS = require('@zeit/next-css')
module.exports = withCSS()
style.css:
样式.css:
.example {
font-size: 50px;
color: blue;
}
package.json:
包.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@zeit/next-css": "^0.1.5",
"next": "^6.0.0",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.4",
"redux": "^4.0.0",
"redux-devtools": "^3.4.1"
},
"scripts": {
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"dev": "next",
"build": "next build",
"start": "next start"
}
}
Questions:
问题:
1.There is an "Uncaught SyntaxError" in Chrome, but it seems to not affect the rendering of the page. But I still wondering the reason and the solution. index.js error in chrome is below img
1、Chrome中存在“Uncaught SyntaxError”,但似乎不影响页面的渲染。但我仍然想知道原因和解决方案。chrome 中的 index.js 错误低于 img


2.As shown in Chrome, there's no "example" class, which means the style.css file is not loaded. Am I missing anything? no CSS file in chrome
2、Chrome中显示没有“example”类,表示没有加载style.css文件。我错过了什么吗?chrome 中没有 CSS 文件


Thanks in advance.
提前致谢。
回答by mtl
EDIT: As of Next.js 7, all you have to do to support importing .css files is to register the withCSSplugin in your next.config.js. Start by installing the plugin:
编辑:从 Next.js 7 开始,支持导入 .css 文件所需要做的就是在next.config.js中注册withCSS插件。首先安装插件:
npm install --save @zeit/next-css
Then create the next.config.jsfile in your project root and add the following to it:
然后next.config.js在您的项目根目录中创建该文件并将以下内容添加到其中:
// 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:
您可以通过创建一个简单的页面并导入一些 CSS 来测试这是否有效。首先创建一个 CSS 文件:
// ./index.css
div {
color: tomato;
}
Then create the pagesfolder with an index.jsfile. Then you can do stuff like this in your components:
然后pages用index.js文件创建文件夹。然后你可以在你的组件中做这样的事情:
// ./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.
您还可以使用带有几行配置的 CSS 模块。有关更多信息,请查看nextjs.org/docs/#css上的文档。
Deprecated: Next.js < 7:
弃用:Next.js < 7:
You'll also need to create a _document.jsfile in your pagesfolder and link to the compiled CSS file. Try it out with the following content:
您还需要_document.js在pages文件夹中创建一个文件并链接到已编译的 CSS 文件。尝试使用以下内容:
// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<html>
<Head>
<link rel="stylesheet" href="/_next/static/style.css" />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
The stylesheet is compiled to .next/static/style.csswhich means that the CSS file is served from /_next/static/style.css, which is the value of the hrefattribute in the linktag in the code above.
样式表被编译成.next/static/style.css这意味着 CSS 文件是从 提供的/_next/static/style.css,这是上面代码中标记中href属性的值link。
As for the first question, it's probably Chrome not understanding the import syntax. Try to enable the Experimental Web Platformflag in chrome:flagsand see if that solves it.
至于第一个问题,可能是 Chrome 不理解导入语法。尝试启用“实验性 Web 平台”标志chrome:flags,看看是否能解决问题。
回答by amin_2c
you need create to custom _document.jsfile.
您需要创建自定义_document.js文件。
Custom document when adding css will look like:
添加 css 时的自定义文档将如下所示:
import React from "react";
import Document, { Head, Main, NextScript } from "next/document";
export default class MyDocument extends Document {
render() {
const { buildManifest } = this.props;
const { css } = buildManifest;
return (
<html lang="fa" dir="rtl">
<Head>
{css.map(file => (
<link rel="stylesheet" href={`/_next/${file}`} key={file} />
))}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
回答by Hamed
As Zeitsaid :
正如Zeit所说:
- Create a /static folder at the same level the /pages folder.
- In that folder put your .css files
- In your page components import Head and add a to your CSS.
- 在 /pages 文件夹的同一级别创建一个 /static 文件夹。
- 在该文件夹中放置您的 .css 文件
- 在您的页面组件中导入 Head 并将 a 添加到您的 CSS。
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
And that's it, this way Next.js should render the link tag in the head of the page and the browser will download the CSS and apply it.
就是这样,这样 Next.js 应该在页面的头部呈现链接标签,浏览器将下载 CSS 并应用它。
Thanks Sergiodxa at Githubfor this clear solution.
感谢Github 的Sergiodxa 提供了这个清晰的解决方案。
回答by Mehrdad Masoumi
If you use next.js do this.
如果您使用 next.js,请执行此操作。
create next.config.jsin root projects
在根项目中创建next.config.js
const withCSS = require('@zeit/next-css');
function HACK_removeMinimizeOptionFromCssLoaders(config) {
console.warn(
'HACK: Removing `minimize` option from `css-loader` entries in Webpack config',
);
config.module.rules.forEach(rule => {
if (Array.isArray(rule.use)) {
rule.use.forEach(u => {
if (u.loader === 'css-loader' && u.options) {
delete u.options.minimize;
}
});
}
});
}
module.exports = withCSS({
webpack(config) {
HACK_removeMinimizeOptionFromCssLoaders(config);
return config;
},
});
Don't forget to restart the server
不要忘记重启服务器
回答by John Carse
Add {name}.cssto src/static/styles/.
添加{name}.css到src/static/styles/.
Then modify the Headin src/pages/_document.jsto include the following link:
然后修改Headinsrc/pages/_document.js以包含以下内容link:
<Head>
<link href="/static/styles/{name}.css" rel="stylesheet">
</Head>
回答by cr05s19xx
For anyone who comes here ,the new Next JS supports CSS out of the box. The catch is that for modules (components), they must be named as the component. So, if you have a header inside a componentsdirectory, it must be named header.module.css
对于来到这里的任何人,新的 Next JS 开箱即用地支持 CSS。问题是对于模块(组件),它们必须被命名为组件。因此,如果components目录中有标题,则必须将其命名为header.module.css

