面试题答案
一键面试1. 优化Webpack配置参数
- 代码分割策略:
- 合理设置
splitChunks
参数,避免将关键的SEO相关代码过度分割。比如对于首页首屏渲染所需的代码,尽量打包在初始chunk中,使其能在页面加载时快速获取。例如:
module.exports = { optimization: { splitChunks: { chunks: 'all', minSize: 30000, minChunks: 1, maxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name(module) { const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]; return `npm.${packageName.replace('@', '')}`; } } } } } };
- 合理设置
- 懒加载插件配置:
- 对于使用的懒加载插件(如
@babel/plugin-syntax-dynamic-import
等),确保其配置正确,不会因插件问题导致懒加载行为异常影响SEO。例如,在Babel配置文件(.babelrc
或babel.config.js
)中正确设置:
{ "plugins": ["@babel/plugin-syntax-dynamic-import"] }
- 对于使用的懒加载插件(如
2. 处理路由懒加载与SEO标签的关系
- 预渲染路由内容:
- 使用预渲染工具(如
prerender-spa-plugin
),在构建时对路由进行预渲染,生成静态HTML文件。这样搜索引擎爬虫访问时可以直接获取完整的页面内容。例如:
const PrerenderSPAPlugin = require('prerender-spa-plugin'); const path = require('path'); module.exports = { plugins: [ new PrerenderSPAPlugin({ staticDir: path.join(__dirname, 'dist'), routes: ['/', '/about', '/contact'], renderer: new PrerenderSPAPlugin.PuppeteerRenderer() }) ] };
- 使用预渲染工具(如
- 动态设置SEO标签:
- 在路由组件懒加载后,及时根据组件内容动态设置SEO标签(如
title
、meta
等)。可以使用react-helmet
(对于React项目)或类似的工具。例如,在React组件中:
import React from'react'; import { Helmet } from'react-helmet'; const MyLazyLoadedComponent = () => { return ( <> <Helmet> <title>My Page Title</title> <meta name="description" content="This is my page description" /> </Helmet> <div>Component content</div> </> ); }; export default MyLazyLoadedComponent;
- 在路由组件懒加载后,及时根据组件内容动态设置SEO标签(如
3. 优化懒加载的时机与触发条件
- 首屏优化:
- 避免首屏内容的过度懒加载。确保首屏展示的核心信息(如文章标题、摘要等重要SEO元素)直接在初始加载时渲染,而不是通过懒加载延迟到后续加载。可以将首屏相关组件设置为非懒加载,或者在Webpack配置中让首屏相关代码打包在初始chunk。
- 可视区域加载:
- 合理设置懒加载的可视区域触发条件。如果是图片懒加载,使用
IntersectionObserver
等技术,设置一个合适的阈值,确保在图片即将进入可视区域时加载,而不是过早或过晚加载,避免影响页面整体渲染和SEO爬虫抓取。例如:
const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; observer.unobserve(img); } }); }); images.forEach(image => { observer.observe(image); });
- 合理设置懒加载的可视区域触发条件。如果是图片懒加载,使用
4. 处理懒加载资源的加载优先级
- 资源优先级设置:
- 在Webpack配置中,对于SEO关键资源(如字体文件、关键CSS样式等),可以通过
resourceHint
等属性设置其加载优先级。例如,对于字体文件:
这样浏览器会根据module.exports = { module: { rules: [ { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', generator: { filename: 'fonts/[name][ext]', publicPath: 'fonts/', resourceHint: 'font' } } ] } };
resourceHint
提示的优先级来加载资源,确保SEO相关资源优先加载。 - 在Webpack配置中,对于SEO关键资源(如字体文件、关键CSS样式等),可以通过