My first library for React! #146609
Replies: 1 comment
|
I think the main issue is that you're mixing Node.js file-system operations with browser-side React code. "fs/promises" is designed for Node.js. It cannot directly read files from a user's browser, and adding Node polyfills may increase your bundle size without solving the underlying architectural problem. I'd suggest separating the two use cases:
Use the browser's File API instead of "fs.readFile()": async function readSvgFile(file) { You can then parse the SVG using "DOMParser": const parser = new DOMParser();
With Vite, you can import it as raw text: import svgText from "./icon.svg?raw";
Since your code uses SVGO, I'd consider running the optimization in a Node.js environment, such as a build script or backend service, rather than importing Node-dependent functionality into the browser bundle. If you need real-time browser-side SVG manipulation, look for a browser-compatible library or use the DOM APIs for the transformations you need. My recommendation: Don't add Node.js polyfills as the first solution. Separate file reading from SVG optimization, and choose the environment based on where the operation runs. Hope this helps! |
Uh oh!
There was an error while loading. Please reload this page.
Select Topic Area
Question
Body
Hi guys!
I'm trying to build my first react library for learning and utilities if could be any chance useful for others.
MindfulLearner/svgestor#14
TL;DR
The error occurs because Vite doesn’t automatically include polyfills for Node.js modules, like fs, which are not compatible with the browser. This happens when I try to use Node.js modules in browser code. The recommended solution is to avoid using Node.js modules in the browser or manually add polyfills, though the latter might not be ideal. In my case, I’m trying to read and manipulate an SVG file in the browser, which causes the issue. It’s better to consider an alternative, like loading the SVG via an HTTP request instead of using fs.
are there any other method?
ty everyone
All reactions