--- nuxt使用@/nuxt/sitemap插件生成sitemap.xml网站地图,利于vue项目seo。 --- # 简介 vue项目是SPA单页面应用,目前很流行做网站但是却非常不利于网站的seo。利用nuxt.js静态化特性能够将vue项目转化为静态网站,正好nuxt使用@/nuxt/sitemap插件也能够生成sitemap.xml网站地图,现在就简单介绍一下如何生成sitemap网站地图。 **先来看下效果:** ![sitemap.png](http://www.codingyun.com/cloud/articles/20221125/12c7678ae1a63ea481605d91bcebf9dc.png)
图一:sitemap.xml
# 一、安装@/nuxt/sitemap插件 ## 1. npm命令安装 ```bash npm i @nuxtjs/sitemap -D ``` ## 2. 在根目录/static下新建sitemap.js ![sitemapjs.png](http://www.codingyun.com/cloud/articles/20221125/c5fd6edb9fe3f7dafa4e25a77dba9e45.png)
图1.2:sitemap.js目录结构
```javascript import axios from "axios"; const sitemap = { path: '/sitemap.xml', //生成的文件路径 hostname: 'http://www.codingyun.com', //网站的网址 cacheTime: 1000 * 60 * 60 * 24, //一天的更新频率,只在generate:false有用 gzip: true, //生成.xml.gz的sitemap exclude: ['/404', '/oauth/login/**', '/oauth/**', '/oauthlogin/**','/category/minxinss','/category/components/**'], //排除不要的页面,这里的路径是相对于hostname defaults: { changefred: 'always', lastmod: new Date() }, routes: async () => { axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? process.env.DEV_API : process.env.PROD_API const articles = await axios.get('/api/articles?current='+1+'&size=1000').then(res => { let proList = res.data.data; // console.log('proList:',proList) var siteArray = []; let siteObject = {}; proList.forEach(item => { siteObject = { url: `/article/${item.id}/`, changefred: 'daily', lastmod: new Date() } siteArray.push(siteObject); }); return siteArray }) return articles } } export default sitemap; ``` ## 3. nuxt.confing.js配置文件中新增配置 主要是以下几行配置: ```JavaScript import sitemap from './static/sitemap' export default { modules: [ '@nuxtjs/sitemap' ], sitemap: sitemap, } ``` 为了方便你参考,放出我的完整配置: ```JavaScript import sitemap from './static/sitemap' export default { // Global page headers: https://go.nuxtjs.dev/config-head head: { title: 'coding云 - 全栈工程师实战项目分享', htmlAttrs: { lang: 'en' }, meta: [ //To avoid any duplication when used in child components, please give a unique identifier with the hid key to the meta description. This way vue-meta will know that it has to overwrite the default tag. { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, // coding云提供超高性价比成熟源码系统及二次开发,为您提供各种管理系统源码公众号/H5/企业网站/小程序/应用软件,售票/票务核销/商城/会员/积分/展览/分销系统,企业管理系统(OA/CRM/ERP),智能仓储物流系统(WMS/TMS/BMS) ], // 这里全局引入js script,也可以在app.html里引入,但是局部引入的需要参考:https://nuxtjs.org/docs/features/meta-tags-seo/ script: [ // { src: 'https://ssl.captcha.qq.com/TCaptcha.js' }, { src: 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.8.3/katex.min.js' }, { src: 'http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=微博appId' }, // qq互联:https://connect.qq.com/index.html { src: 'http://connect.qq.com/qc_jssdk.js', 'data-callback':true, 'data-appid':'**', 'charset':'utf-8', 'data-redirecturi':'***', } ], //在 Nuxt.js 应用中使用外部资源 link: [ { rel: 'icon', type: 'image/png', href: '/favicon.png' }, { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/github-markdown-css/2.2.1/github-markdown.css' }, { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.8.3/katex.min.css' }, { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900' }, { rel: 'stylesheet', href: 'https://fastly.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css' } ] }, // https://nuxtjs.org/announcements/going-full-static/ target: 'static', // https://nuxtjs.org/docs/configuration-glossary/configuration-generate/ generate: { // 不生成articles文件夹下加index.html方式,直接是articles.html // subFolders: false interval: 100 //两个渲染周期之间的间隔,以避免使用来自 Web 应用程序的 API 调用互相干扰,我理解的应该是静态化时调用接口的频率,单位毫秒 }, router: { extendRoutes(routes, resolve) { // // 扩展路由,让 nuxt 支持静态页面请求,如 https://www.xxx.cn/index.html routes.push( // { // name: "htmlArticles", // path: "/article/:id"+".html", // component: resolve(__dirname, "pages/article/_id.vue") // }, // { // name: 'index.html', // path: '/', // component: resolve(__dirname, 'pages/index.vue'), // }, // { // name: 'oauthQQ', // path: '/oauthlogin/qq', // component: resolve(__dirname, 'pages/oauth/OauthLogin.vue'), // }, { name: 'oauthQQ', path: '/oauth/login/qq', component: resolve(__dirname, 'pages/oauth/OauthLogin.vue'), },{ name: 'oauthWb', path: '/oauth/login/weibo', component: resolve(__dirname, 'pages/oauth/OauthLogin.vue'), } ) }, }, // Global CSS: https://go.nuxtjs.dev/config-css // npm install --save-dev sass sass-loader@10 css: [ '@/assets/css/index.css', '@/assets/css/iconfont.css', '@/assets/css/markdown.css', '@/assets/css/vue-social-share/client.css', '@/node_modules/highlight.js/styles/atom-one-dark.css', '@/node_modules/nprogress/nprogress.css', 'animate.css/animate.css' ], server: { port: 3000, // default: 3000 // host: '0.0.0.0', // default: localhost, timing: false, // https: { // key: fs.readFileSync(path.resolve(__dirname, 'server.key')), // cert: fs.readFileSync(path.resolve(__dirname, 'server.crt')) // } }, render: { resourceHints: false, //禁用预加载 asyncScripts: true }, // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins //插件只在浏览器里使用,这种情况下下,你可以用 ssr: false ,使得插件只会在客户端运行 plugins: [ '@/plugins/filters',//全局过滤器 {src: '@/plugins/global.js', ssr: false}, // {src: '@/plugins/vue-infinite-loading.js', ssr: false}, {src: '@/plugins/vue-baberrage.js', ssr: false}, {src: '@/plugins/vue-avatar-cropper.js', ssr: false}, {src: '@/plugins/share.js', ssr: false}, {src: '@/plugins/markdown.js'}, // '~/plugins/axios.client.js', //前端客户端 // '~/plugins/axios.server.js', //前端服务端 // '~/plugins/axios.js', //前端客户端 + 前端服务端 {src: '~/plugins/axios.js'} ], // Auto import components: https://go.nuxtjs.dev/config-components components: true, // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules buildModules: [ // https://go.nuxtjs.dev/eslint '@nuxtjs/eslint-module', // https://github.com/nuxt-community/vuetify-module // npm install --save @nuxtjs/vuetify // Simple usage '@nuxtjs/vuetify' ], // Modules: https://go.nuxtjs.dev/config-modules modules: [ // npm install --save @nuxtjs/style-resources '@nuxtjs/style-resources', // https://go.nuxtjs.dev/axios '@nuxtjs/axios', '@nuxtjs/sitemap', // Simple usage // 'cookie-universal-nuxt', // With options ['cookie-universal-nuxt', { parseJSON: true }], //https://github.com/nuxt-community/legacy-modules/tree/master/packages/toast '@nuxtjs/toast', ], sitemap: sitemap, toast: { position: 'top-center', register: [ // Register custom toasts { name: 'myError', message: 'Oops...Something went wrong', options: { type: 'error', keepOnHover: true, duration: 2000 } } ] }, // Axios module configuration: https://go.nuxtjs.dev/config-axios axios: { proxy: true, // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308 baseURL: "http://localhost:3000", browserBaseURL: "http://localhost:3000", }, /* ** proxy */ proxy: { // '/api/': { target: 'http://localhost:8085', pathRewrite: {'^/api/': ''} } "/api": "http://www.codingyun.com" }, publicRuntimeConfig: { axios: { browserBaseURL: process.env.VUE_APP_BASE_URL_API } }, privateRuntimeConfig: { axios: { baseURL: process.env.BASE_URL } }, // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify vuetify: { // customVariables: ['~/assets/variables.scss'], defaultAssets: { font: false, icons: 'mdi' }, treeShake: true, theme: { dark: false } }, // Build Configuration: https://go.nuxtjs.dev/config-build build: { extractCSS: true, /** 将css单独打包成一个文件,默认的是全部加载到html **/ // analyze: true, // postcss: { // plugins: { // cssnano: { // preset: [ // "default", // { // calc: false // } // ] // } // } // }, // //分割vendor.app.js文件(打包优化) optimization: { runtimeChunk: { name: 'manifest' }, splitChunks: { chunks: 'all', cacheGroups: { libs: { name: 'chunk-libs', chunks: 'initial', priority: -10, reuseExistingChunk: false, test: /node_modules\/(.*)\.js/ }, styles: { name: 'chunk-styles', test: /\.(scss|css)$/, chunks: 'all', minChunks: 1, reuseExistingChunk: true, enforce: true } } } } } } ``` # 二、重新调用nuxt generate命令生成静态化页面 ```bash npm run generate 或者 nuxt generate ``` ## 生成静态页部署,generate之后打开dist目录可以看到生成了sitemap.xml ![sitemapxml.png](http://www.codingyun.com/cloud/articles/20221125/d72faac5439310d2dab5d0c954c1c8b1.png)
打赏
  • 微信
  • 支付宝

评论
来发评论吧~