Errors
First let's go through your errors a little bit:
When you don't use npm run build
or npm run start
, you won't use webpack and therefore the require
statement doesn't get replaced with the contents of the fs
module--instead you are left with a require statement, which your browser doesn't understand since require is a Node-only function. Thus, your error about require not being defined.
If you do run with npm run build
or npm run start
, webpack takes that require statement out and replaces it with the fs
module. But, as you've discovered, fs
doesn't work on the client side.
Alternatives
So, if you can't use fs
to save files, what can you do?
If you are trying to save the file to a server, you have to submit data from your form to the Node server, and the Node server can use fs
to interact with the server's filesystem to save the file.
If you are trying to save the form locally, i.e., on the same device as the browser, you need to use another strategy like this or by using a client-side library like FileSaver. Which option you take depends somewhat on your use case, but if you are trying to save on the client side you can search around "saving files from web browser" or "saving files client side" to see what works for you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…