How to change module.exports to import and export? - javascript

module.exports = function (idx) {
this.camera = idx;
};
module.exports.CONFIG = function () {
return Promise.resolve([]);
};
module.exports.CONFIG.FLOOR = function () {
return Promise.resolve([]);
}
I have a file that contains code like above.
I require this file and console.log it. It only shows
function (idx) {
this.camera = idx;
}
Why other attributes are hidden?
And if I delete first module.exports paragraph and console.log it, it shows an anonymous function(or default function ?) in CONFIG.
{ CONFIG:
{ [Function]
FLOOR: [FUNCTION]
}
}
I am wondering how to change it to import/export type instead of module.exports/require?
Thanks!

It looks like you have both named exports and a default export. When exporting, that would look something like:
// Default export:
export default function (idx) {
this.camera = idx;
};
function CONFIG() {
return Promise.resolve([]);
}
CONFIG.FLOOR = function () {
return Promise.resolve([]);
}
// Named export:
export CONFIG;
Then, when importing them, you need to both import the default and the named:
import idxFn, { CONFIG } from '../foo';
^^^^^ default import
^^^^^^ named import
You'll then be able to access FLOOR by referencing CONFIG.FLOOR.
But, note that having a function which is a property of another function is really weird. You might consider exporting FLOOR as another named export instead, just like CONFIG:
// Default export:
export default function (idx) {
this.camera = idx;
};
// Named exports:
export function CONFIG() {
return Promise.resolve([]);
}
export function FLOOR () {
return Promise.resolve([]);
}

Related

Use exported value in setup of Vue Composition API

In a plain js file the code looks like
export default async function exportData() {
const { data } = await store
.dispatch('fetchData')
const { bookings } = data
const booking = bookings.length ? bookings[0]._id : ''
const event = {
bookingID: booking
}
// other methods and variables
return {
.....
}
}
inside the vue file
import exportData from './exportData'
export default {
setup() {
const {
fetchEvents,
isEventActive,
} = exportData()
fetchEvents()
}
}
the problem is in vue components the values from exportData gets undefined, gets error fetchEvents is not a function when the export is asynchronous. works well if not asynchronous. what is the workaround here??
You can try to declare fetchEvents,isEventActive methods in plan js file without wrapping it inside any function
const fetchEvents = () => {
//body
};
const isEventActive = () => {
//body
};
and export them as
export {fetchEvents, isEventActive};
now use them
import {fetchEvents,isEventActive} from 'path-to-js-file'
export default {
setup() {
fetchEvents()
isEventActive()
}
}

Is it possible to export default arrow function with just one line in TypeScript?

const func: () => void = () => {
console.log('I CAN export my function in this way');
};
export default func;
export default () => void = () => {
console.log('I CANNOT export my function in this way (Parsing error: Expression expected.)');
};
As above code shown, we can always declare and assign a function in both ways. However, I cannot export the arrow fucntion with same syntax by export default. How come?
Thanks in advance
You can't export something as default with a type annotation on the same line. If you wanted to do it in a one-liner while retaining the function signature you could do it as a named export:
export const func: () => void = () => {
console.log('I CAN export my function in this way');
};
the importing file would then import like this:
import {func} from 'path'
or...
You'd have to rip off the function signature:
export default () => {
console.log('I CAN export my function in this way')
}
Then import it as whatever:
`import bloopityBloop from 'path'`
You sure can export default and apply a type/interface in one statement...
export default (
() => {
console.log('I CAN export my function in this way');
}
) as () => void;

ES6 Uncaught TypeError: Object(...) is not a function

I'm returning a Promise from this function
const liab_config = () => {
return axios.get(`${config.server_url}/fetch_config_liab`);
}
export default { liab_config }
And trying to handle the Promise inside another file
import liab_config from './utils/kc-adapter'
function set_liab_config(){
liab_config().then((response) => {
if(response.data.success){
let { kc_config_liab } = response.data;
return kc_config_liab['auth-server-url'];
}
else
return null;
}).catch(ex =>
console.log(ex));
}
Here I'm getting the error as:
Uncaught TypeError: Object(...) is not a function
on line liab_config().then((response). What could be the reason?
You're default-exporting an object literal. You want to use either a named export
const liab_config = …;
export { liab_config as liab_config }
// shorter:
const liab_config = …;
export { liab_config }
// or just:
export const liab_config = …;
with
import { liab_config } from './utils/kc-adapter'
or a default export
const liab_config = …;
export { liab_config as default }
// or just:
default export const liab_config = …;
// or without the local name:
default export …;
with
import liab_config from './utils/kc-adapter'
When you are accessing something like this
import liab_config from './utils/kc-adapter'
It means you are asking for the default export which must be written like
const liab_config = () => {
return axios.get(`${config.server_url}/fetch_config_liab`);
}
export { liab_config as default };
or like this
const liab_config = () => {
return axios.get(`${config.server_url}/fetch_config_liab`);
}
export default liab_config;
And if you don't want to make it default then pass it like
export const liab_config = () => {
return axios.get(`${config.server_url}/fetch_config_liab`);
}
or
const liab_config = () => {
return axios.get(`${config.server_url}/fetch_config_liab`);
}
export { liab_config };
And access it like
import {liab_config} from './utils/kc-adapter'

Exporting function in ES6 / react

On the server side (nodejs/express), I have no problems in exporting and referencing this file (using Attempt1).
// collectionFile.js
function collection() {
let data = {};
function getData(key) {
return data[key];
}
function setData(key, value) {
data[key] = value;
}
return {
getData: getData,
setData: setData
};
}
const instanceOfCollection = collection();
On the client side (React), I'm just not able to reference and access the getData function. Below are some of the combination I tried. None of them work. How can I make it work ?
// Attempt1: export
// module.exports.getter = instanceOfCollection.getData;
// Attempt1: import
// const getter = require('./collectionFile').getter;
// Uncaught TypeError: getter is not a function
// Attempt2: export
// export default { instanceOfCollection };
// Attempt2: import
// import instanceOfCollection from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined
// Attempt3: export
// export const instanceOfCollection = collection();
// Attempt3: import
// import { instanceOfCollection } from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined
Edit: Turns out that I was referencing File A from File B and also File B from File A earlier
There are a lot of ways to do such things:
ES5 export
module.export = instanceOfCollection
then
var getData = require('my_module').getData
ES6 export
export default instanceOfCollection
then
import { getData, setData } from 'my_module'
ES6 named export
export const setter = instanceOfCollection.setData
export const getter = instanceOfCollection.getData
then
import { setter, getter } from 'my_module'
or
import * as myCollection from 'my_module'
myCollection.getter()
myCollection.setter()
ES5 with renaming
module.export = {
getter: instanceOfCollection.getData,
setter: instanceOfCollection.setData,
}
then
const { setter, getter } = require('my_module')
or
const getter = require('my_module').getter
const setter = require('my_module').setter
Hope some of them will work for you.

Exported Function isn't a Function?

Not sure why it's not viewing this as a function:
impl.js
export default function(callback){
return callback();
};
test.js
import {myModule} from '../../src/impl.js'
import {expect} from 'chai';
const module = myModule;
describe('', () => {
it('should callback when resolve is invoked', () => {
module(resolve => {
resolve('test');
}).then(value => {
expect(value).to.equal('test');
});
});
});
Error: TypeError: module is not a function
module isn't a function because where it receives its value, myModule, also isn't a function.
And, that is because you aren't using quite the correct syntax to import the export default. For that, you'll want to remove the braces around myModule:
import myModule from '../../src/impl.js'
From MDN:
Syntax
import *defaultMember* from *"module-name"*;
With the braces, the import will match a particular export by its name.
import { myModule } from '...';
Corresponds to either:
export let myModule = ...;
export function myModule() { ... };
And, impl.js doesn't export anything actually named myModule.
You don't have an export with name myModule. You only have a default export.
Either use a named export
export function myModule() { ... }
or import the the module properly
import myModule from '...';
See the export documentation on MDN for more info.

Categories

Resources