3

I am working on a React v16 app and need to load a heavy (IMO) library for xlsx export of data.

I'm using functional components/hooks.

I understand and have used the <Suspense /> component and lazy for lazy loading modules. but since this item is not a component, it is simply a library function i need to run with an onClick event, i can't use lazy/suspense.

How can i lazy load this function only when needed? (writeXlsxFile)

import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
//...
import writeXlsxFile from "write-excel-file";

//...
  const fileCreate = async () => {
    await writeXlsxFile(exportData, {
      schema,
      fileName: `file.xlsx`,
    });
  };

return(//...
sao
  • 1,835
  • 6
  • 21
  • 40
  • 1
    Can you clarify what you mean by "this function"? Do you mean fileCreate or writeXlsxFile? – Urmzd Nov 10 '21 at 15:31
  • i just updated it cuz i was thinking the same thing, kinda vague. the writeXlsxFile function is what i want to lazy load – sao Nov 10 '21 at 15:32
  • but if i import at the top of file, its not lazy loading. i need it to selectively load only when needed, aka, when the user needs to use it – sao Nov 10 '21 at 15:36
  • 2
    In any case, `named` imports can be lazy loaded by way of `async`. Ex: `async () => { const writeXlsxFile = await import ('write-excel-file'), // Whatever you want here}` – Urmzd Nov 10 '21 at 15:38
  • 1
    does this https://stackoverflow.com/a/64208216/5690068 answer your question? dynamic import will work, you just need to access it by `module.default` – seanplwong Nov 10 '21 at 16:08

1 Answers1

4

JavaScript, and by direct association, React, supports Dynamic Imports.

So,

const fileCreate = async () => { 
  const {default: writeXlsxFile} = await import ('write-excel-file')
  void await writeXlsxFile(exportData, {
      schema,
      fileName: `file.xlsx`,
  });
}
Urmzd
  • 682
  • 4
  • 17
  • bummer im getting a "writeXlsxFile" is not a function error, i did update the names to match, you had writeXlsx, which is updated to writeXlsxFile – sao Nov 10 '21 at 15:53
  • 1
    @sao you're still getting the error after updating the names? – Urmzd Nov 10 '21 at 16:02
  • yeah its still there – sao Nov 10 '21 at 16:06
  • 1
    Updated @sao. It passed my mind that you're using a `default` import instead of a `named` import (even though `default` imports can be imported by name). – Urmzd Nov 10 '21 at 16:09
  • you got it dude. the second rendition works. i'll have to read up on the default setting. thank you! – sao Nov 10 '21 at 16:10