i.brod
i.brod

Reputation: 4603

How to import a file using ES6 modules, and read its content as a string?

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?

Upvotes: 5

Views: 4244

Answers (2)

adanski
adanski

Reputation: 805

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

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()
    );
}

Upvotes: 0

happyZZR1400
happyZZR1400

Reputation: 2405

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!

Upvotes: 2

Related Questions