面试题答案
一键面试1. 正确设置meta标签
在Next.js中,可以利用next/head
组件来设置页面的meta标签。对于多语言网站,根据不同语言版本动态设置meta标签内容。
假设在pages/post/[id].js
页面,有不同语言的文章标题和描述,可如下实现:
import Head from 'next/head';
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id } = router.query;
const { locale } = router;
let title, description;
if (locale === 'en') {
title = 'English Article Title';
description = 'English article description';
} else if (locale === 'zh') {
title = '中文文章标题';
description = '中文文章描述';
}
return (
<>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
</Head>
<h1>{title}</h1>
<p>{description}</p>
</>
);
}
2. URL结构优化
为了满足SEO要求,URL结构应简洁且包含语言信息。在Next.js中可以通过自定义路由规则来实现。
例如,在next.config.js
中配置:
module.exports = {
async rewrites() {
return [
{
source: '/:locale/post/:id',
destination: '/post/[id]'
}
];
}
};
这样,通过/:locale/post/:id
这种URL结构,既能区分不同语言版本,又能被搜索引擎友好识别。比如/en/post/123
表示英文版本的文章123
,/zh/post/123
表示中文版本的文章123
。
3. 示例完整代码
假设项目目录结构如下:
pages
├── post
│ └── [id].js
└── index.js
next.config.js
pages/post/[id].js
完整代码:
import Head from 'next/head';
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id } = router.query;
const { locale } = router;
let title, description;
if (locale === 'en') {
title = 'English Article Title';
description = 'English article description';
} else if (locale === 'zh') {
title = '中文文章标题';
description = '中文文章描述';
}
return (
<>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
</Head>
<h1>{title}</h1>
<p>{description}</p>
</>
);
}
next.config.js
代码:
module.exports = {
async rewrites() {
return [
{
source: '/:locale/post/:id',
destination: '/post/[id]'
}
];
}
};
通过上述设置,不同语言版本的页面在meta标签设置和URL结构方面都能较好地满足SEO要求。