How to use index.js in project? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have the following project structure:
/app
/components
/TextInputs
SearchInput.js
TextInput.js
/Buttons
Button.js
CircleButton.js
/screens
...
/utils
...
/services
...
/theme
theme.js
I have seen people using index.js files for importing/exporting stuff, in order to clean all imports of the app.
Is this the main purpose of index.js? Is it a good practice to have a index.js per directory?

If you need to import multiple files from a folder like:
import {SearchInput} from './components/TextInputs/SearchInput'
import {TextInput} from './components/TextInputs/TextInput'
I would recommend creating an index file. This reduces the amount of import statements you are going to use in other components:
/app
/components
/TextInputs
SearchInput.js
TextInput.js
index.js
with the content: (/TextInputs/index.js)
import {SearchInput} from './SearchInput'
import {TextInput} from './TextInput'
export {SearchInput, TextInput}
and use it on the other components like:
import {TextInput, SearchInput} from './components/TextInputs'
This is why the index.js is used mostly, and makes the imports more managable and readable for some cases. Entirely up to developer!

It's likely more personal preference than not, but I think indexes has 2 main benefits.
It lets your user know that this file is the key and main file for that directory, like if I see an index.scss in /style I immediately assume that index will #import other partials. If I see an index.js in a root dir I immediately assume it's probably what package.json is referring to. So in a sense it's communicating things to you.
Most typescript/react project will allow importing with index without having to specify the index file and it will automatically load it for you.
// ./src/example/index.js
import Example from './src/example'
...
// ./theme/index.scss
import './theme'
Which will automatically import the index.
This also helps a lot when you're using something like css modules or styles per component where it's stored in the same directory, so that you can still import the normal component without having to do something like import Header from './Header/header.js'.
There is a caveat though, while it serves some benefits it can also be difficult to debug sometimes when you have 20 files called index, when one of them breaks and the debugger is only telling you it's in a file called "index.js" without being more specific about which file or what directory.

Related

Importing js modules by directory name

I'm upgrading a React application and have found that I need to modify the import statements to get them to work.
For example, in the old version, the following import works without errors:
import { User } from '../System'
Note that System is a directory on my file system that contains User, a js file that ends with export default User.
In my upgraded version of the app, the System directory still exists, but the above import gives me Can't resolve '../System' in 'C:\my app\.
It turns out that to get the import working properly now, I need to change it to the following:
import User from '../System/User';
If I understand correctly, this relates to js module system changes made with ES6.
My question, though, is regarding the specification of a directory in the import statement (System above). Why would it be that I was previously able to name a file directory in the import statement instead of the actual js script/module itself? Is that approach of using a directory in the import statement still possible? And if so, is it ever advisable?
Update: based on AKX's comment, I noticed the System directory does indeed contain an index.js, which apparently is what makes the import from the directory itself possible.
When an import points to a directory, and only a file, Webpack (which most React setups use) follows Node's's conventions and will attempt to import index.js from that directory if it exists. That's the only condition under which importing from a path that points to a directory works - your previous build probably had /System/index.js (which would allow importing with from '../System'). If you rename the file you're importing to anything else - such as to User.js - importing using only the directory path will fail.
And if so, is it ever advisable?
Sure, if you want. It's a style choice but is commonly done.

Javascript: importing React from Electron renderer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am using VSCode on Windows. I have set up a boilerplate ElectronJS app and want to use React for the UI. I have main.js, index.html, preload.js and renderer.js.
I have installed these and other packages (like babel) via npm. I see react and other packages in node_modules/ however I can't figure out how to get React imported.
Here is my project structure
node_modules/
.gitignore
index.html
main.js
preload.js
renderer.js
In my renderer.js file I have done as I see other people demonstrate:
import React from 'react';
import ReactDOM from 'react-dom';
In the Electron app's developer console I see: Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".
So I have switched to:
import React from './node_modules/react'
(In the dev console: Failed to load resource: net::ERR_FILE_NOT_FOUND)
For all of these options (separately!):
import React from './node_modules/react/index.js'
import React from './node_modules/react/umd/react.development.js';
import React from import React from './node_modules/react/cjs/react.development.js';
(because it looks like that file reads a Node environment variable to export up either the Dev or Prod version, so it seemed like it might be my entry point) I get "The requested module ... does not provide an export named 'default'.
This will work:
import * as React from 'react';
import * as ReactDOM from 'react-dom';

exporting .png files from a library to a React JavaScript project

I'm creating a utility project that will supply React components and resources to my other projects.
I'd like it to include a set of images (mostly .png files for icons) that can then be imported by the child projects.
I can't figure out how to make this work.
I can export the images from the library, and I can see them, name-mangled, in the node_modules of the child project. So, all good so far.
But, import {imgName} from "myLib" does not include the file in the child project's bundle.
It looks to me like my problem is explained by a clue in https://create-react-app.dev/docs/adding-images-fonts-and-files/:
You can import a file right in a JavaScript module. This tells
webpack to include that file in the bundle.
Presumably, CRA is not triggering this webpack behavior in my case, since I'm importing from another module, not from a file.
How can I get things working?
Assume:
I have complete ownership of the library and child projects, so I can change this solution in whatever way works. I just want to have a single common resource for the images.
I don't want to eject my child projects
Ideally, any complexity should be in the library project. The child projects should have minimal complex tooling. (My intent is for this library to be used by a team of other developers, who will want to focus on their own tasks; not on tooling details)
EDIT (ADDED LATER)
Per the comments in the first answer below, I've created a simple example of my problem. See:
Library repo: github.com/deg/media-file-bug-library
Library package: npmjs.com/package/media-file-bug-library
Client repo: github.com/deg/media-file-bug-client
Just pull the client repo and do yarn install and yarn start. This will bring up a little web page that shows the problem:
SCREEN SNAPSHOT:
The Problem is Not in CRA Trigger. Importing Png File like JavaScript Hides a Magic. Here you are importing a Image and Exporting it which then get Processed by bundler and The Bundled Index Actually Exports The name of the Processed Image File Which in Your Case is corss~nAalnlvj.png. That's Why Your Image is Broken but you are able to render name of File, The Case is Same for microbundle or parcel.
How You Can solve it is by separating your assets and components By Placing Images on separate assets folder and place your images there and then add assets to files in your files in package.json
{
.
.
"files": [ "dist", "assets"],
}
And Then Import Image & Using Like This
import React from 'react'
import ico_cross from 'media-file-bug-library-fix/assets/cross.png'
function App() {
return (
<div className="App">
<img src={ico_cross} alt="im"/>
</div>
);
}
For Further Reference Checkout
Here
A Npm Library For Your Fix I Published Npm media-file-bug-library-fix
enter image description here
hey David I found the solution please do check the above screenshot
as in you package just change in index.modern.js
// WebPack doesnt listen as a path it listen
// var cross = "cross~nAalnlvj.png";
// use import rather than simple name as it generate a full absolute path at parent level so that in child level it can be accessible as an Image
import cross from "./cross~nAalnlvj.png"

Do not import "index.js" on folder import?

I am wondering if it is possible to re-configure the import behavior (looking for index.js) on importing module folders directly. By default, when you assume this module folder structure:
/components
/Button
/index.js
/style.scss
/Checkbox
/index.js
/style.scss
I can easily import the components like this:
import Button from 'components/Button';
import Checkbox from 'components/Checkbox';
But when I am working on that components, I will have multiple index.js files open in my editor/ide which will lead to confusion very quickly. Same applies for the style files.
What I did now is changing my folder structure to this:
/components
/Button
/Button.js
/Button.scss
/Checkbox
/Checkbox.js
/Checkbox.scss
Which solved that problem and I can see directly where each opened file belongs to.
However, now my component imports look a bit... verbose:
import Button from 'components/Button/Button';
import Checkbox from 'components/Checkbox/Checkbox';
Because obviously, webpack/babel would look for an "index.js" when I am importing a folder directly. Now my question is: can I change that behavior somehow? I'd like to tell webpack/babel that it should try to import a file named the same way as the folder as the index file.
You can re-configure directory indexes on every webserver, so I am hoping the same is possible with webpack/babel but googling didnt show anything up so far.
I went with the following solution:
In each of my folders, I will create a index.js next to the "real" module, that has the follwing content:
import module from './Button.js';
export default module;
This way I am able to keep my code in Button.js but am not required to import Button/Button someplace else.
I created a little script which automates the creation of the index.js files for me, so I don't have any additional work.

Benefit of index.js in component folder

I see a tendency of having an index file in the component/container/module folders of react or angular2 projects e.g.
angular2-webpack-starter
react-boilerplate
What is the benefit of this? When should it be used? Why simply naming the file same as the component it contains not enough?
Is for symplicity in the imports. In the style guide in Angular2 documentation, specifictly in the seccion Create and Import Barrels, explain that is a technique for improve the number of files that are nessesary import when you use several elements of a component.

Categories