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(//...
5
  • 1
    Can you clarify what you mean by "this function"? Do you mean fileCreate or writeXlsxFile? Commented Nov 10, 2021 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 Commented Nov 10, 2021 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 Commented Nov 10, 2021 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} Commented Nov 10, 2021 at 15:38
  • 1
    does this stackoverflow.com/a/64208216/5690068 answer your question? dynamic import will work, you just need to access it by module.default Commented Nov 10, 2021 at 16:08

1 Answer 1

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`,
  });
}
Sign up to request clarification or add additional context in comments.

5 Comments

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 you're still getting the error after updating the names?
yeah its still there
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).
you got it dude. the second rendition works. i'll have to read up on the default setting. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.