How to Export Variables with a Dynamic Names - javascript

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

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';

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 multiple components

I have a shared folder that I expose as an npm module.
inside that share folder I have a components folder with index.js that exports them as default:
export { default as AqMegaMenu } from "./megaMenu/AqMegaMenu.vue";
export { default as AqDetailsCard } from "./AqDetailsCard.vue";
export { default as AqDoughnutChart } from "./charts/AqDoughnutChart.vue";
...
My entry file for the library is main.js and i'd like to expose my entire components through it, so I import them in other projects like this:
import {Comp1, Comp2} from "#my/shared"
Currently I export them one by one in main.js:
export { default as AqDetailsCard } from "./components/AqDetailsCard.vue";
...
But i was wondering if there is a way to export the entire components directory using it's index.js
and still be able to import it in other projects like i showed above.
You may try something like this
import camelCase from 'lodash/camelCase'
const requireModule = require.context('./components', true, /\.vue$/)
const modules = {}
requireModule.keys().forEach(filename =>
{
const moduleName = camelCase(fileName.match(/([^\\\/]+)\.vue$/)[1]);
modules[moduleName] = requireModule(fileName)
})
export default modules

Multiple exports from react.js file

I have a react.js file MyComponent that has this at the end:
module.exports = MyComponent, where MyComponent is a function defined in the file.
What if I want to export ANOTHER function: MyHelperComponent from the same file, so that another react component from another react.js file may use MyHelperComponent directly ?
So my question is: how do I export a function that is not the 'main' component of the module ?
You can only export one value from a module.
If you need to use multiple values outside it, then you need to group them somehow. Typically you would put them in an object and then export that object.
module.exports = { MyComponent, MyHelperComponent };
And then:
const MyComponent = require("./mymodule.js").MyComponent;
const MyHelperComponent = require("./mymodule.js").MyHelperComponent;
or
const mymodule = require("./mymodule.js")
const MyComponent = mymodule.MyComponent;
const MyHelperComponent = mymodule.MyHelperComponent;
or
const {MyComponent, MyHelperComponent} = require("./mymodule.js");
That said, it is usual to structure code on a one-component-per-module basis, so you might want to rethink doing this in the first place.
You can do it like this:
//...function defs here
MyComponent.helper = MyHelperComponent
module.exports = MyComponent
And then just access MyComponent.helper(args) to call the helper function.
You can export like this: export { component1, component2 }
And use like this: import { component1, component2 } from './url'
or
import * as components from './url'
<components.component1 />
Hope helpful...

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