3

My file layout is as follows:

// Folder structure:
//    |-src
//        |-util
//             |-index.js
//             |-PageScreen1.js
//             |-PageScreen2.js (and etc...)
//        |-PageScreen.js
//        |-index.js

I would like to import all of util into PageScreen. At the top of PageScreen.js I put

import * as All from ./util

but this results in a module not found error. Could I get some advice on how to solve this issue?

EDIT: I've added an index.js folder as suggested in one of the answers below. Everything works if I import/export the PageScreens like

import PageScreen1 from './PageScreen1';
import PageScreen2 from './PageScreen2';

export {PageScreen1, PageScreen2}; 

However I have many PageScreen.js files, so is there a way to quickly import/export all of them?

Justin Hu
  • 77
  • 7
  • util is a folder not a file with modules. May be you should try: import * as All1 from ./util/PageScreen1.js import * as All2 from ./util/PageScreen2.js – srujana bhamidipalli Dec 18 '20 at 22:29
  • 2
    Does this answer your question? [Is it possible to import modules from all files in a directory, using a wildcard?](https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard) – Peter B Dec 18 '20 at 22:31
  • @PeterB i added an index.js file inside of my util folder. There, I am able to follow the answer you sent me and manually import PageScreen1/2. However, if I have many PageScreens, I do not want to manually import / export all of them. Is there something like import * that I can use for index.js? From the answer you sent me it seems like its not possible but I hope there is an actual way to do what I want – Justin Hu Dec 18 '20 at 22:40

2 Answers2

1

You need an index.js inside the util directory.

It should import everything from all the other files and then export them again.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • Okay, I created an index.js file within my util directory. Inside of it I did import * as All from 'util', then did export default All. This does not seem correct as I'm unable to access All.PageScreen1 from the outer index.js. I'm quite inexperienced with ReactJS. – Justin Hu Dec 18 '20 at 22:30
  • edit: I manually imported each individual file and exported them as export {PageScreen1, PageScreen2} but is there a way to just import all and export all from the index file? I have many pagescreens and do not want to manually type it all out – Justin Hu Dec 18 '20 at 22:37
1

To import every file you need to add one more slash. it should be ./util/ . You are missing a slash By default in your case react is importing util/index.js

import * as All from './util/'

other ways (organized) can be as follows: inside index.js you can export all files and then get them into outer space

import PageScreen1 from './PageScreen1'
....

export default {PageScreen1,PageScreen2}