nextjs前端在组件中加载外部css文件
时间: 2024-05-09 22:15:00 浏览: 14
在 Next.js 中,在组件中加载外部 CSS 文件有两种方式:
1. 使用 `<link>` 标签
在组件的 `render` 方法中,可以使用 `<link>` 标签来加载外部 CSS 文件。例如:
```
import Head from 'next/head';
const MyComponent = () => (
<div>
<Head>
<link rel="stylesheet" href="path/to/your/css/file.css" />
</Head>
{/* Your component's content */}
</div>
);
export default MyComponent;
```
这种方法会将 CSS 文件作为页面的 `<head>` 部分的一部分来加载,但是仅限于在客户端(浏览器)中加载。
2. 使用 `import` 语句
在组件的 JavaScript 文件中,可以使用 `import` 语句来加载外部 CSS 文件。例如:
```
import styles from 'path/to/your/css/file.css';
const MyComponent = () => (
<div className={styles.container}>
{/* Your component's content */}
</div>
);
export default MyComponent;
```
这种方法会将 CSS 文件作为模块来加载,并将其作为 CSS 模块化样式(CSS Modules)应用于组件中。这种方法适用于服务器端渲染和客户端渲染。