面试题答案
一键面试- 配置
next.config.js
:- 在项目根目录找到
next.config.js
文件,如果没有则创建一个。 - 在该文件中添加如下代码:
- 在项目根目录找到
module.exports = {
assetPrefix: '',
webpack(config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'special - static/[name].[ext]',
publicPath: '/static/',
outputPath:'static/special - static'
}
}
]
});
return config;
}
};
- 目录结构与资源放置:
- 确保你的
special - static
目录在项目根目录下,里面存放着相应的图片、字体等静态资源。例如,special - static/logo.png
。
- 确保你的
- 使用资源:
- 在组件中,你可以像这样引用这些资源:
import Image from 'next/image';
function MyComponent() {
return (
<div>
<Image
src="/static/special - static/logo.png"
alt="logo"
width={200}
height={100}
/>
</div>
);
}
export default MyComponent;
- 这里通过
next/image
组件引用了自定义静态文件服务路径下的图片。对于字体等资源,在 CSS 中引用时路径也需遵循/static/special - static/
这个规则。例如:
@font - face {
font - family: 'MyFont';
src: url('/static/special - static/myfont.woff2') format('woff2'),
url('/static/special - static/myfont.woff') format('woff');
font - weight: normal;
font - style: normal;
}
这样就可以实现通过 /static/special - static
路径访问 special - static
目录下的静态资源。