• 导航

NuxtJS V2 优化

前端杂烩 2024-04-04 22 次浏览

移除未使用的CSS

      
    render: {
route: (url, result) => {
// Tailwindcss 内联到 html 中是未压缩的,原因未知
// 所以在 render 时使用 cleanCSS 压缩
const { html } = result;
const STYLE_PATTERN = /]*>([\s\S]*?)<\/[^>]*style>/gi;
const replaceHTML = html.replace(STYLE_PATTERN, ($0, $1) => {
const context = [];
context.push('');
return context.join('');
});
result.html = replaceHTML;
},
}

动态增加Script

      
  hooks: {
route: (url, result, { req }) => {
// 支付宝小程序,需要加入特定的 js
// 目前轻交互会在小程序打开
const { headers } = req;
const { html } = result;
const userAgent = headers['user-agent'] || '';
const isAliAPP = userAgent.toLocaleLowerCase().includes('aliapp');
if (!isAliAPP) {
return;
}
const aliAPPScript =
'';
result.html = html.replace(/<\/head>/i, aliAPPScript);
},
}

减少__Nuxt__体积

NuxtJS 在使用服务端渲染时,会自动往HTML注入当前页面使用的数据,对于只有渲染的页面,在客户端根本用不到这些数据,如果是列表页面,这些数据会偏大,导致整个页面体积变大,造成传输耗时。
诉求是:把用不到的这些数据在页面渲染时去掉。
方案是:利用 NuxtJS 提供的渲染 Hook 解决,代码如下:
      
  hooks: {
'vue-renderer': {
'ssr:templateParams': (templateParams, renderContext) => {
const { APP } = templateParams;
const { nuxt } = renderContext;
const { ...state } = nuxt;
const { config } = state;
// 去掉 window.__NUXT__ 没有用的信息,只保留环境信息,减少页面体积
// 环境信息是必须的,不能去掉
const PATTERN = /`;
});
Object.assign(templateParams, {
APP: replaceHTML,
});
},
},
},

增加页面级缓存

在 middleware 新建 page-cache.js ,代码如下:
      
  const LRU = require('lru-cache');
export const CACHE = new LRU({
// 缓存队列长度 最大缓存数量
max: 100,
// 缓存时间 单位:毫秒
maxAge: 1000 * 60 * 60 * 24,
});
export default (req, res, next) => {
if (process.env.NODE_ENV !== 'production') {
next();
return;
}
const cacheKey = 'NPS_PAGE';
const cacheObj = CACHE.get(cacheKey);
if (cacheObj) {
res.setHeader('Content-Type', ' text/html; charset=utf-8');
res.end(cacheObj.html, 'utf-8');
return;
}
res.original_end = res.end;
res.end = (data) => {
if (res.statusCode === 200) {
CACHE.set(cacheKey, {
html: data,
});
}
res.original_end(data, 'utf-8');
};
next();
};
在 nuxt.config.js 中启用:
      
   serverMiddleware: ['~/middleware/page-cache.js'],
    

增加模版变量

uxtJS 在渲染页面时,只有固定几个变量,比如:APP、ENV、HEAD 等。而这些远远满足不了自定义的需求。
举个现实的场景:项目中,有些页面使用灵犀系统上报埋点,有些页面不使用,如果把灵犀代码放到统一的页面入口中,对于不使用灵犀的页面而言,反而增加了一个多余的网络请求,影响页面性能。
我们的诉求是,能根据页面路径,动态的追加灵犀代码。
这就需要借助 NuxtJS 提供的 Hooks 来支持。在 nuxt.config.js 增加 hooks ,代码如下:
      
  hooks: {
'vue-renderer': {
'ssr:templateParams': (templateParams, renderContext) => {
const { nuxt } = renderContext;
const { routePath } = nuxt || {};
const whiteList = [
'/light-portal.html',
'/light-portal/material-detail.html',
'/light-portal/material.html',
];
// 只有特定页面才加入灵犀
const shouldAppendLX = whiteList.includes(routePath);
// 追加 IS_APPEND_LX 全局变量,便于在页面中使用
Object.assign(templateParams, {
IS_APPEND_LX: shouldAppendLX,
});
},
},
}
在 app.html 使用 「IS_APPEND_LX」变量动态输出 灵犀脚本:
      
  {% if (IS_APPEND_LX) { %}


{% } %}