I've tried the below:
const fs = require('fs');
var file = fs.readFileSync("../word.txt", {encoding: 'utf8'}).toString()
but get the error Module not found: Error: Can't resolve 'fs'
. All I want is to be able to store all the .txt contents into a variable that I can manipulate. What other easy ways are there as I don't think there's any easy way to bypass this error.
Thanks a lot and please help!!
CodePudding user response:
There are two (well three, see below) ways to load the contents of a text file that is bundled with your React project.
- Put the file in the
Bonus round - custom webpack config
Customise your Webpack config to add a resource query to load modules using source assets
module: { rules: [ // ... { resourceQuery: /raw/, type: 'asset/source', } ] },
and import your text file contents using
import word from "./path/to/word.txt?raw";
If you're using
create-react-app
, this will require ejecting your configuration.
The JSON option
If you don't mind encoding your text file content into a JSON string literal, you can always use a
.json
file.For example,
assets/word.json
"this is some plain text in a JSON file"
import jsonFileContents from "./assets/word.json";