最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to load local text file into string variable in ReactNative Project? - Stack Overflow

programmeradmin2浏览0评论

In my ReactNative project there are some static text files which i'd like to load into a string variable. Like this way:

var content = loadPlainTextFile("resources/tags.txt");
var tags = content.split("\n");

I tried require in the same way i'm requiring javascript files, but it doesn't work because react native gives exception "Unable to resolve module ./data/tags.txt".

var customData = require('./data/tags.txt');

I guess that require() is not able to handle plain text files?

How to do correctly?

In my ReactNative project there are some static text files which i'd like to load into a string variable. Like this way:

var content = loadPlainTextFile("resources/tags.txt");
var tags = content.split("\n");

I tried require in the same way i'm requiring javascript files, but it doesn't work because react native gives exception "Unable to resolve module ./data/tags.txt".

var customData = require('./data/tags.txt');

I guess that require() is not able to handle plain text files?

How to do correctly?

Share Improve this question edited Apr 11, 2016 at 16:35 delete asked Apr 9, 2016 at 13:09 deletedelete 19.1k17 gold badges62 silver badges98 bronze badges 3
  • show us example of content of tags.txt file – Ivan Chernykh Commented Apr 9, 2016 at 13:54
  • 1 its a plain list of words, line by line – delete Commented Apr 9, 2016 at 14:46
  • 3 Your question is legitime. Why is it so easy to require JS files, JSON files, even binary files (images), but not a simple text file. Of course we export any string with export default "some useful text" but we are loosing the type, and syntax highlighting, which is a shame. Example of some useful extensions: config.yml query.grapql shader.glsl – Joseph Merdrignac Commented Jun 18, 2018 at 10:12
Add a comment  | 

2 Answers 2

Reset to default 17

The question is specifically asking about how to import a text file using something like:

import textFile from './textFile.txt'

This is possible using React-Native-Local-Resource. The library allows you to asynchronously load any type of text file.

Create a constants.js like below, where you are exporting the constants.

module.exports = {
  SPRING_CONFIG: {tension: 40, friction: 3},
  COLOR: {
    COLOR1: '#ffffff',
    COLOR2: '#eeeeee',
    BLACK_TEXT: '#333',
  },
};

Then in whatever file you are trying to import it, import it as...

import CONSTANTS from './constants'; //Make sure you put the right folder path.
console.log(CONSTANTS.COLOR.BLACK_TEXT);
发布评论

评论列表(0)

  1. 暂无评论