how to import Helper class in react - javascript

I am creating a helper class in react. The image below shows my setup:
In my App.js, I have:
import Helpers from './Helpers.js'
I have also tried:
import Helpers from './components/Helpers.js'
import Helpers from 'src/components/Helpers.js'
import Helpers from './components/Helpers.js'
import Helpers from 'src/components/Helpers.js'
import {Helpers} from './components/Helpers.js'
import {Helpers} from 'src/components/Helpers.js'
and I have also tried, in my Helpers.js:
export default Helpers
export default Helpers();
However, I receive an error message:
'./Helpers.js' does not contain an export named 'Helpers'.
It seems as though App.js can not find and locate this class. How can I import it, so i can just call the functions, like:
Helpers.helperFunctionHere();
thanks.

Option 1: Export each function individually
In Helpers.js
export function helperFunctionHere() {
console.log("hello there");
}
In App.js
import {helperFunctionHere} from "./Helpers";
render() {
helperFunctionHere();
}
Option 2: Static properties on the class
In Helpers.js
class Helpers {
static helperFunctionHere() {
console.log("hi");
}
}
export default Helpers
In App.js
import Helpers from "./Helpers";
render() {
Helpers.helperFunctionHere();
}

Should be export default Helpers. Am also assuming that your bundler is setup correctly.

Related

Problem when importing from another folder in React Typescript

I have the following folder structure
I want to import both MessageList.tsx and MessageSent.tsx inside my Chat.tsx
// Chat.tsx
import React from 'react'
import {MessageList, MessageSent} from "./components/"
type Props = {}
const Chat= (props: Props) =\> {
return (
<div\>Chat</div>
)
}
export default Chat`
// MessageSent.tsx
import React from 'react'
type Props = {}
const MessageList = (props: Props) => {
return (
<div>MessageList</div>
)
}
export default MessageList
MessageList.tsx is similar to MessageSent,tsx, only the name of the components is different
However, when I try to do the import of these two components {MessageList, MessageSent} I get the following error:
** Cannot find module './components/' or its corresponding type declarations.**
Why is that?
Tried different paths besides "./components/", even with full path.
You can either import the components one by one
import MessageSent from "./components/MessageSent"
import MessageList from "./components/MessageList"
or create an index directory file (index.ts)
import MessageSent from './MessageSent'
import MessageList from './MessageList'
export { MessageSent, MessageList }
To be able to import from components you need index.ts file in components folder.
// index.ts
export * from './MessageList';
export * from './MessageSent';
Add a new file named index.ts inside your components folder
Then write this in the index.ts
export * from './MessageList.tsx';
export * from './MessageSent.tsx';

How to import js file into svelte

I am building an app in svelte and I have a helper.js file inside /src folder where I am going to put helper functions.
I am trying to import the helper.js file into the GetData.svelte file:
GateData.svelte:
<script>
import Helper from "./helper.js";
let helper = new Helper();
</script>
helper.js:
class Helper {
constructor() {
console.log("hello world");
}
}
main.js:
import App from './App.svelte';
const app = new App({
target: document.body,
});
export default app;
However, the error message I get is:
==>> Uncaught ReferenceError: Helper is not defined (main.js 6)
Do I have to import the helper.js file in the main.js as well?
Thank you for any help.
You need to export your class in helper.js:
export class Helper {
// ...
}
and then import it in main.js as
import { Helper } from "./helper.js";
Or, if you only want to export this one class from the helper file, you can use
export default class Helper {
// ...
}
and import as you currently do:
import Helper from "./helper.js";

Having Trouble Accessing Function in Adjacent JS file

Currently in my directory I have App.js and startMenu.js as two separate files.
I would like to access startMenu.js in my App.js file with the correct React formatting.
Currently I can call the function startMenu() using typical javascript syntax, but I for some reason cannot get the React syntax {startMenu} to work. Any ideas would be appreciated.
My code:
import React from "react";
import startMenu from './startMenu';
import credits from "./credits";
var param = 'start';
class App extends React.Component {
renderSwitch(param) {
switch(param) {
case 'credits':
return credits();
default:
/*LINE IN QUESTION */
return startMenu();
}
}
render() {
return (
<div>
{this.renderSwitch(param)}
</div>
);
}
}
export default App;
Thanks!
It is depending how you are exporting your function.
If is doing this:
export default startMenu;
Then you might import that way:
import myFunction from './path';
That way the name does it care. You can call your function with any name when you are exporting by default.
But if you are exporting that way:
export { startMenu };
or
export startMenu;
So than you need import your function by your reall name, and if you are exporting just using export word, all members will be inside an object.
So you need do that:
import MyFunctions from './path';
or doing a import destruction
import { startMenu } from './path';
You'll need to properly export that function:
export function startMenu(...) { ... }
Then import it:
import { startMenu } from './startMenu';
If that's the only thing exported you can always export default and it simplifies the import.
You can only import things that have been exported. Everything else is considered private and is off-limits.
The JSX syntax: {foo} means "Put this data here".
It doesn't mean "Call this variable as a function".
If you want to call it, you need to do so explicitly: {foo()}.

How to Export Variables with a Dynamic Names

I have a components folder in nuxt.js
/components/atoms/
and inside that folder I have an index.js to export all components dynamically
const req = require.context('./', true, /\.vue$/)
const components = {}
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
components[componentName] = req(fileName).default
})
export const { ButtonStyled, TextLead, InputSearch } = components
so I can import perfectly as I wish
import { ButtonStyled } from "#/components/atoms"
the problem is that I am defining the variables to be exported statically, fixed, so for each created component I would need to add another variable manually
I need to dynamically export the variable name
Example:
DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']
export const { DynamicCreation } = components
// output -> export const { ButtonStyled, TextLead,InputSearch } = components
I need to export the name of already unstructured variables
Note: I can not use this export default components because I can not import like this import { ButtonStyled } from "#/components/atoms"
You should be able to do it like this:
export default components
Then in your file where you want to use the components:
import * as components from '#/components/atoms'
Then when you need to use the components in your Vue files, you need to map them:
#Component({
components: {
ButtonStyled: components.ButtonStyled
}
})
And now you have:
<ButtonStyled></ButtonStyled>
You can make something like this way, check if is what do you need.
Create a file to import a conjunct of components: allComponents.js
export default {
componentOne: require('./passToOneComponent.js');
componentTwo: require('./passToOneComponent.js');
componentThree: require('./passToOneComponent.js');
}
After in index.js export the allComponents.js with the name that you wish:
export {default as SomeName } from 'allComponents.js';
So in the final file, you can make something like:
import { SomeName } from 'index.js';
SomeName.componentOne();
I created a library that does this type of export, anyone who wants can install via npm
I created a Webpack Plugin that makes named exports from a component, maybe this helps other people
Weback Plugin - named-exports

ES6 exporting/importing in index file

I am currently using ES6 in an React app via webpack/babel.
I am using index files to gather all components of a module and export them. Unfortunately, that looks like this:
import Comp1_ from './Comp1.jsx';
import Comp2_ from './Comp2.jsx';
import Comp3_ from './Comp3.jsx';
export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;
So I can nicely import it from other places like this:
import { Comp1, Comp2, Comp3 } from './components';
Obviously that isn't a very nice solution, so I was wondering, if there was any other way. I don't seem to able to export the imported component directly.
You can easily re-export the default import:
export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';
There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.
Also, bear in mind that if you need to export multiple functions at once, like actions you can use
export * from './XThingActions';
Too late but I want to share the way that I resolve it.
Having model file which has two named export:
export { Schema, Model };
and having controller file which has the default export:
export default Controller;
I exposed in the index file in this way:
import { Schema, Model } from './model';
import Controller from './controller';
export { Schema, Model, Controller };
and assuming that I want import all of them:
import { Schema, Model, Controller } from '../../path/';
default export
// Default export (recommended)
export {default} from './module'
// Default export with alias
export {default as d1} from './module'
all export
// In >ES7, it could be
export * from './module'
// In >ES7, with alias
export * as d1 from './module'
function name export
// export by function names
export { funcName1, funcName2, …} from './module'
// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './module'
destructured object export
// export destructured object
export const { myVar, myFunction } = myObjectWithEverything
// export destructured object, with renaming
export const { v1: myVar, f1: myFunction } = myBigObject
with array
// it works with array as well
export const [ funcName1, funcName2 ] = myBigArray
More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
Folder structure:
components|
|_ Nave.js
|_Another.js
|_index.js
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
I've been searching for years how to export modules as both, named exports, and default exports in modular JavaScript. After tons of experimenting, the solution I found is quite simple and efficient.
// index.js
export { default as Client } from "./client/Client.js";
export { default as Events } from "./utils/Events.js";
// Or export named exports
export { Client } from "./client/Client.js";
export { Events } from "./utils/Events.js";
export * as default from "./index.js";
This would allow each exported module to be imported in two ways:
// script.js
import { Client } from "index.js";
new Client();
import module from "index.js";
new module.Client();
// You could also do this if you prefer to do so:
const { Client } = module;
You can mess around with this to have it suit your needs, but it works for me. Hope it helps!
What worked for me was adding the type keyword:
export type { Comp1, Comp2 } from './somewhere';
Install #babel/plugin-proposal-export-default-from via:
yarn add -D #babel/plugin-proposal-export-default-from
In your .babelrc.json or any of the Configuration File Types
module.exports = {
//...
plugins: [
'#babel/plugin-proposal-export-default-from'
]
//...
}
Now you can export directly from a file-path:
export Foo from './components/Foo'
export Bar from './components/Bar'
Good Luck...

Categories

Resources