Export a function from a JavaScript file - javascript

I am trying to make a component in React that is just a function
import React from "react";
function TableSortFunction(data, method, column) {
const newList = [];
for (let i; i <= data.length; i++) {
newList.push(data[i].column);
}
console.log(newList), data, method, column;
return newList;
}
export default TableSortFunction;
I am importing my function in another component like this
import { TableSortFunction } from "./TableSortFunction";
but I get an error saying:
Attempted import error: 'TableSortFunction' is not exported from './TableSortFunction'.
How do I export a js file that is just a function?

Since you export it as default you have to import it like so:
import TableSortFunction from "./TableSortFunction";
Edit: Another issue with your code is that the following is not syntactically correct.
console.log(newList), data, method, column;
Try this instead:
console.log(newList, data, method, column);

Try this
import TableSortFunction from "./TableSortFunction";
Your console isn't correct
instead of
console.log(newList), data, method, column;
should be
console.log(newList, data, method, column);
There are two types of import - named and default.
Export and Import function
Export from - say.js
function sayHi(user) {
alert(`Hello, ${user}!`);
}
function sayBye(user) {
alert(`Bye, ${user}!`);
}
export {sayHi, sayBye};
Import from - say.js to main.js
import {sayHi, sayBye} from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!
for better understanding, you can refer to articles.
Export and Import
Named Export vs Default Export in ES6

Related

Export function not working in JavaScript

I have been working on a shopping list application in React but have ran into a problem with exporting a regular JavaScript function from a file called webscrape.js into my react App.js I have tried multiple different ways of exporting but I keep getting this error.
Thanks to any help in advance.
Module not found: Can't resolve 'readline' in
'C:\Users\USERNAME\Desktop\Programming-Projects\Counter
App\counter-app\node_modules\puppeteer\lib\cjs\puppeteer\node'
This is the end of my webscrape file where I export a test function
function testExport(){
console.log("Test Export");
}
function testExport2(){
console.log("Test Export 2");
}
export {testExport, testExport2}
This is the start of my App.js where I import and try using the function
import NavBar from "./components/navbar";
import PriceBar from "./components/pricebar";
import "./App.css";
import Counters from "./components/counters";
import fs from 'fs';
import data from "./shoppingData.json";
import {testExport, testExport2} from "./webscrape.js";
//test export
testExport();
You should use export default {testExport, testExport2}.
But, looking throught your errors, seems like the error it's related to puppeter. Do you have puppteer added to your node_modules? Did you make a npm i?
Try:
export const testExport = () => {
console.log("Test Export");
}
export const testExport2 = () => {
console.log("Test Export 2");
}

call react component-element as variable

Is it possible to call a React component element with a variable inside?
import React from "react"
/*React functional component*/
function someName() {
const someVar = "componentName"; //the name of the called component
return(
<{someVar}/>
)
}
export default someName;
I try to implement this in a router and to change the filenames(Sites) (in the element) dynamically with useState from fetched data.
I am open to all kind of help :)
There is no direct way to do that but you can use this approach.
import ComponentA from '...path';
import ComponentB from '...path';
...
const components = {
componentA: ComponentA,
componentB: ComponentB,
...
}
...
function App(props) {
const TargetComponent = components[props.componentName];
return <TargetComponent />;
}

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()}.

Javascript export default and import

I have the following code:
const API1 = new API({
...
})
const API2 = new API({
...
})
export default { API1, API2 }
I need to import like this:
import API1 from '/lib/api'
API1.get()...
But it doesn't work.
I don't want to do this:
import blah from '/lib/api'
blah.API1.get()...
How can I solve this ?
Thanks.
If you need to export multiple items, and don't want to have to create two variables in the consuming module (one for the default import - the object, and another for the API1 property), your only other option is to change the default export to a named export, allowing you to import just one particular named property:
const API1 = new API({
...
})
const API2 = new API({
...
})
export { API1, API2 }
and
import { API1 } from '/lib/api'
API1.get()...
The export { syntax indicates that the export is named, rather than default, and the import { syntax indicates that you're importing a named import, rather than a default import.
(It looks a lot like destructuring, and it's a little bit similar, but it's not the same)
Since you're default exporting an object you need to access individual property to access there methods, Instead you can use named exports
// exporting values
export const API1 = new API({
...
})
export const API2 = new API({
...
})
// Importing values
import { API1 } from '/lib/api'
API1.get()...

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

Categories

Resources