2

In my standard React app, I need to achieve the following: import a file that sits within my src folder, in order to simply read its content as a string. For example, let's say I have the following code in a file:

alert('hey') 

then in some other file, I would like to do something like this, in pseudo code:

import * as string from './someFile.js'

console.log(string)

The output of the console.log should be the JS code, as a string:

alert('hey')

If I could place the file within my public folder, I'd be able to perform an http request and read it as I wish. But the problem is of course, that the file is part of the build process(inside the src folder)

Can this be done?

i.brod
  • 3,993
  • 11
  • 38
  • 74
  • Is it specifically javascript file content? – GBourke Dec 15 '21 at 09:00
  • If this is only part of build you can just use the node fs module...[Read a file in Node.js](https://stackoverflow.com/questions/18386361/read-a-file-in-node-js) – pilchard Dec 15 '21 at 09:13
  • @pilchard Maybe I misspoke. What i mean, is that the file is part of the puzzle that webpack assembles from the files. The fs module isn't available during runtime, and this is when I need to read the file. – i.brod Dec 15 '21 at 12:23
  • @Gandzal Yes it's js. – i.brod Dec 15 '21 at 12:24

2 Answers2

1

i can think about:

  1. define constants.js file with following code:

    export default "alert('vasia')";
    
  2. import this file from some react file:

    import vasia from "./constants";
    
    const App = () => {
      console.log(eval(vasia));
    }
    

is that what you r searching for?

But, must warn you: "eval" is evil!

happyZZR1400
  • 2,387
  • 3
  • 25
  • 43
0

I wanted to do the very same thing but unfortunately found out it is not possible in pure JS as at 2022.

There's a stage 3 TC39 proposal for Import Assertions which is available in Chromium-based browsers but only allows to import JSON files so it certainly would not help in this particular case.

I believe your best bet for now is to use Fetch API to get the content of your file asynchronously.

async function getSampleText() {
    const response = await fetch('someFile.js');
    console.log(
        await response.text()
    );
}
adanski
  • 471
  • 6
  • 12