1.0.0 • Published 3 years ago

html-webpack-prefetch-rpc v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

html-webpack-prefetch-rpc

Introduction

一种 rpc请求时机 提前到 head中 的 预加载方案

usage

npm i -D html-webpack-prefetch-rpc

step1、webpack.config#plugins 添加插件

plugins: [
  ...,
  new HtmlWebpackPrefetchRpcPlugin({
    files: [{
      match: /homework\/index\.html/, // 设置匹配的页面
      dataUrlQueryRegx: /data_url=([^&]*)/ // 设置 url query中获取 data cdn url字段的正则
    }]
  })
]

step2、项目中添加 prefetchRpc 方法

  const prefetchRpc = (
    dataCdnUrl: string,
    fetchRpcPromise: () => Promise<any>,
  ) => {
    return new Promise((resolve, reject) => {
      const prefecthData = window.prefetchRpcData?.[dataCdnUrl];
      if (window.enablePrefetchRpc && prefecthData) {
        // 开启缓存 && 缓存数据存在
        resolve(prefecthData);
      } else {
        // 从线上rpc读取
        fetchRpcPromise()
          .then(data => {
            resolve(data);
          })
          .catch(err => {
            reject(err);
          });
      }
    });
  };

step3、项目中使用 prefetchRpc 来代替原来的 获取数据方法

原来 获取rpc数据的方法

const dataUrl = 'xxxx';
axios.get(dataUrl, { timeout: 20000 }).then(res => {
  if (res.status === 200 && res.data) {
    resolve(res.data);
  } else {
    reject(new Error('获取数据异常'));
  }
});
const dataUrl = 'xxxx';
prefetchRpc(dataUrl, () => {
  return new Promise((resolve, reject) => {
    // 原来 获取rpc数据的方法
    axios.get(dataUrl, { timeout: 20000 }).then(res => {
      if (res.status === 200 && res.data) {
        resolve(res.data);
      } else {
        reject(new Error('获取数据异常'));
      }
    });
  });
})

License

1.0.0

3 years ago

0.0.18-0

3 years ago

0.0.15-0

3 years ago

0.0.17-0

3 years ago

0.0.16-0

3 years ago

0.0.13-0

3 years ago

0.0.12-0

3 years ago

0.0.11-0

3 years ago

0.0.10-0

3 years ago

0.0.9-0

3 years ago

0.0.8-0

3 years ago

0.0.7-0

3 years ago

0.0.6-0

3 years ago

0.0.5-0

3 years ago

0.0.4-0

3 years ago

0.0.3-0

3 years ago

0.0.2-alpha7

3 years ago

0.0.2-alpha6

3 years ago

0.0.2-alpha4

3 years ago

0.0.2-alpha3

3 years ago

0.0.2-alpha2.0

3 years ago

0.0.2-alpha

3 years ago

0.0.1

3 years ago