What does import * do in Javascript? - javascript

I was browsing through this repo on Github and was trying to comprehend the working of the code
Here, the author (or programmer) have mentioned import * at multiple places so I am trying to comprehend and understand how import * work?
First in Game.js file of his repo he have mentioned/written like this
import * as actions from '../actions';
In VS Code, when if I click on '../actions using command It is redirecting me to this file -> index.js
then in Index.js they have something like this
import * as ActionTypes from './action-types';
when I click on ./action-types it redirects me to here action-types.js
I went through firefox docs but I wasn't able to clearly make sense for the first example like for one, the action folder contains multiple files and how does import * as actions from '../actions'; mean index.js file
While i get he have called/referenced the functions using actions.functionName() or ActionType.TypeName
My Prime question remains
how does import * as actions from '../actions'; mean index.js file ?

The import * as name syntax imports all exported content of a javascript file.
For example, if you want to import an entire module's contents, then access the doAllTheAmazingThings() function
import * as myModule from '/modules/my-module.js';
myModule.doAllTheAmazingThings();
From the docs

Import in js is new syntax of ES6 to import a module it has the same work of require but its easier to filter what do you want in a module
In your example you import * as actions from '../actions'; you import all function from ../actions file
its same to do const actions = require('../actions')
but its easier to manage what you want
this syntax is not work on all browser so be sure to use transpiler with babel or other
you can see this syntax in python too

When you reference a directory in an import statement, it looks and loads the index.js file in that directory. What I usually do there is export classes and functions under that directory in a grouped object, so they can be easily accessed:
For instance in index.js I export sth like:
{
Class1,
method1
}
where each is imported as such:
import Class1 from './Class1';
So they just group the classes/methods/... that are in files in the directory.
Then you can easily access it as such:
import { Class1, method1 } from './mymodule';
vs
import Class1 from './mymodule/Class1';

Related

Globally importing ReactJS components in all files

In React when you wanna import components from other files we use:
import ComponentName from 'somePlace';
That works fine, but I wanna know if there is a way to import the content of a file instead of the exports. I wanna put all import statements for components in a single file (e.g. imports.js) and have a statement like:
import './import.js' to all documents;
so all my components are automatically imported everywhere.
Is there a way to do that?
Globally import modules? Not really, no. And neither should you need to.
A hacky "solution" would be assigning all imports to the global context (e.g. window in the browser) so it's accessible that way. That's possible, but definitely not recommended. It'll also prevent your bundler (most likely Webpack) from optimizing a lot of code.
Apart from the technical aspect, there are other reasons not to do so. If you specify the imports in each file, you know exactly what imports that file needs and under what variables it is imported as for that file.
If you still want to simplify importing the same components over and over again, you can have this setup:
imports.js
// For default exports
import ComponentA from 'wherever';
export { ComponentA };
// For regular exports
//import { ComponentB } from 'wherever';
export { ComponentB } from 'wherever';
// For whole modules
//import * as wherever from 'wherever';
export * as wherever from 'wherever';
someOtherFile.js
// Either import as a namespace
import * as Imports from './imports';
console.log([
Imports.ComponentA,
Imports.ComponentB,
Imports.wherever.someFieldFromTheWhereverModule,
]);
// Or partial import
import { ComponentA, ComponentB } from './imports';

Import 2 JavaScript functions with the same name in Angular project

I imported JavaScript files into Angular project like this: https://www.truecodex.com/course/angular-6/how-to-use-external-js-files-and-javascript-code-in-angular
It's all working fine. However, there is one problem. I have 2 JavaScript files that I imported that have the same name. So, when I use it in my component's typescript like this:
declare const CMenu: any
there is a name collision between those 2 functions.
Is there a way to import JavaScript files, just for one particular Angular module. For example, to specify in Angular.json in which module to import the JavaScript file. I actually have a lot of JS files that use same function names, and I need to use those from 2 different modules (each module using different function with the same name).
You can import it with an alias on the page where you need it.
import CMenu as CeeMenu from 'locationA';
import CMenu as CMenu from 'locationB';
declare const a:CeeMenu;
declare const b:CMenu;
These imports can be joined in one file, exporting them with an alias, hence you can import them from one location.
import CMenu as CeeMenu from 'locationA';
import CMenu as CMenu from 'locationB';
export CeeMenu as AA, CMenu as BB;
then
import AA, BB from 'locationC';
declare const a:AA;
declare const b:BB;

How to import a file that already imports another file?

Javascript, ES6. I have three files:
inline-functions.js
\*
Bunch of small functions.
*/
some-module.js
import './inline-functions.js'
// uses many inline functions
main.js
import './inline-functions.js'
import './some-module.js'
// uses inline functions as well as classes from some-module.js
Now, I use Visual Studio Code and I would like Intellisense working but when I am editing main.js, it only shows functions from inline-functions.js and everything from 'some-module.js' is unreachable even though there is an import statement. However, when I comment the import out of some-module.js like this:
// import './inline-functions.js'
// tries to use inline functions which are now not callable
Intellisense suddenly shows correct names and documentation for all objects. This is of course unusable because some-module.js now can't call any of the inline functions.
What is the correct way of importing these modules?
You can access the module function only if you export it from the module.
Export the function form the module then you will see it in main js.
Example:
some-module.js
import './inline-functions.js'
const someFuncion1 = () => 1;
const someFuncion2 = () => 2;
export {
someFuncion1,
someFuncion2
}
main.js
import * as inline './inline-functions.js'
import * as some './some-module.js'
//Access it like
inline.<function name>
some.<function name>

reexport all files from a folder webpack

We're using a folder structure like this
components
| Button.js
| Nav.js
| ...etc
| index.js
somefolder
|somefile.js
in the inderx file we're importing every component and reexporting it like this
// index.js
import Button from './Button'
import Nav from './Nav'
export {Button, Nav}
this way we can import many components into a file like this
// somefile.js
import {Button, Nav} from '../components'
Maintaining that index file is a bit of a pain though and discourages flexible use of components. I know that Webpack can import many files with a syntax like this
function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('./components/', true, /\.js$/));
however, I didn't yet find a way to reexport all of these components to use them like above.
The desired outcome is to replace the index.js file with something that automates the process of bundling all the files from a folder without having to add every file manually.
I think getting rid of the file index will not be the best solution and may cause questions from other developers. But I can offer a slightly more simplified way:
index.js:
export * from './some-component1.js';
export * from './some-component2.js';
some-component1.js:
export {SomeComponent1};
some-component2.js:
export {SomeComponent2};

ES6 modules import is undefined

I'm trying to figure out an issue I have with ES6 modules import.
This is a very simplified version of what I'm attempting to do. My current file structure is much more complicated with nested folders.
I have 2 ReactJS components:
/buttons
/MyComponent1.js
/index.js
/texts
/MyComponent2.js
/index.js
/index.js
My files look something like this:
I'm importing the MyComponent2 from the root index.js file which is the entry-point of my package.
MyComponent1.js
import MyComponent2 from '../../';
export default () => (
<div><MyComponent2 /></div>
);
MyComponent2.js
export default () => (
<div>Hello world</div>
);
My buttons/index.js and texts/index.js files export all components in their own folder:
buttons/index.js
export { default as MyComponent1 } from './MyComponent1';
texts/index.js
export { default as MyComponent2 } from './MyComponent2';
And my root index.js export all my folders to make them publicly available. It's my entry-point:
export * from './buttons';
export * from './texts';
So when I import MyComponent2 in MyComponent1 from the root index.js file, it's undefined. When I import it from ./MyComponent2.js, it's defined. When I import the entire package in another project and import MyComponent2 from the root index.js file, it's defined.
It's mind-blowing and I don't understand why I can't import MyComponent2 from the root index.js file.
I need to do that because I have a set of hundred of components nested in different folder and I want to make them all available from this entry-point file.
Can someone tell me what is happening and how to make this possible?
Thanks
Okay, took me a while to figure out what is happening. Please take a look at the sandbox i've setup - https://codesandbox.io/s/nk0qmo096j
I've tried to keep the folder/module structure similar to what you've described. Please look through how the folder/modules are structured before you continue reading.
When you run the code in the sandbox, take a look at the console. You'll see something like this -
So let me try to explain why what you're trying to do is not working
buttons/MyComponent is the first file to be "exported" (since its at the bottom of the dependency chain; Project/index -> components/index -> buttons/index -> buttons/MyComponent)
Note that components/index has not been exported yet, so it will return undefined
Then buttons/index is exported, followed by texts/index
Then buttons/MyComponent is rendered; just before it is rendered i manually require components/index and it is now defined so returns some defined value
In essence, when your MyComponent1 is trying to import MyComponent2 via the index file, the index file has not been exported yet so it returns undefined. To work around this, you have to require MyComponent2 from within MyComponent1's render method.
you can import all the components from the respective component files and then assign them to a variable in the root component and then export all of them as objects.
import MyComponent1 from './buttons/index'
import MyComponent2 from './texts/index'
export {MyComponent1, MyComponent2}
to import this components in another file or project. you could import only one them using object destructuring.
import {MyComponent1} from 'index.js'
import {MyComponent2} from 'index.js'
In my case, I had an old js file that the IDE imported instead of the updated ts file. so if your module file is module.js make sure there isn't a compiled old module.js in the same directory

Categories

Resources