首页 > 解决方案 > 如何使用外部 css 在 nuxtJS 中创建 amp 页面

问题描述

在我的项目上尝试了@nuxtjs/amp,主要问题是:

在“nuxt.config.js”文件中的“extractCss”是真的,它适用于所有布局&我不能为我的 ampLayout 做任何例外

为了制作一个有效的 amp 页面,我需要将所有 CSS 代码放入内部

无论如何要保留 {"extractCss": true} 并为 amp 页面例外?

标签: nuxt.jsamp-html

解决方案


这个对我有用。尝试:

nuxt.config.js

{
  hooks: {
    // This hook is called before generatic static html files for SPA mode
    'generate:page': ({ page }) => {
      if (/^\/amp\//gi.test(page.path)) {
        page.html = modifyHtml(page.html)
      }
    },
    // This hook is called before rendering the html to the browser
    'render:route': (url, page) => {
      if (/^\/amp\//gi.test(url)) {
        page.html = modifyHtml(page.html)
      }
    }
  }
  
}

修改HTML

const modifyHtml = (html) => {
  const styleConcat = renderSync({ file: 'assets/css/amp.scss', outputStyle: 'compressed' }).css.toString()
  html = html.replace('</head>', `<style amp-custom>${styleConcat}</style></head>`)
  html = html.replace(/<link[^>]*rel="stylesheet" href=".*\.css[^>]*>/gi, '')
  html = html.replace(/<link[^>]*rel="preload" href=".*\.js[^>]*>/gi, '')
  return html
}


推荐阅读