0

I'm absolutely baffled by this one...

In my React project with create-react-app, I have a standalone js file in which I'd like to read a string from a txt file. The txt file is part of a project and not on a server.

I can't seem to find any answers of how to complete this seemingly trivial task in a synchronous manner. These would seem like obvious options:

import text from './data/text.txt';

const text = require('./data/text.txt');

Both lines above return a new path that includes /static/media/, which I can access through localhost in the browser, but that doesn't help me.

I can use JSON but it's almost a matter of principle at this point. It just seems ridiculous that I can't read a simple txt file.

1
  • It is not a trivial task in react (a client side library). You should have a input with type file and then use FileReader object or Blob to read content of the file. Commented Jun 12, 2019 at 4:53

1 Answer 1

1

You can use webpack raw-loader to directly import raw files into your project.

Install:

$ npm install raw-loader --save-dev

Config:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
    ],
  },
};

Usage:

import text from './data/text.txt';
console.log(text);  // This line will print out the content of the text file in the console
Sign up to request clarification or add additional context in comments.

Comments

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.