.then() on node modules not working? - javascript

I'm working on a react native app right now and I wrote my own module to store some information separated from my components.
While I did that I noticed that in my module I created, I had a function like this:
testFetch = function(url){
return fetch(url);
}
exports.test = testFetch;
In my main module I did the following:
import ts from 'test-module'
ts.test("http://example.com").then((response) => {console.log(response)});
But .then() is not getting fired for any reason. The request went through and was successful.
Any help on this?

The problem is the way you mix CommonJS and ES6 modules. You seem to expect that ts in your example main module gives you the value of the whole export in your module dependency, but that's not how it works.
You can use export default to export your testFetch function, like so:
testFetch = function (url) {
return fetch(url);
}
export default testFetch;
Main module:
import testFetch from 'test-module';
testFetch("http://example.com").then((response) => {console.log(response)});

Related

SyntaxError: Cannot use import statement outside a module nextjs Vercel [duplicate]

Trying out Next.js but I'm struggling with the following. Just tried to install react-hook-mousetrap and imported it like I normally would:
import useMousetrap from "react-hook-mousetrap";
This gives me the following error:
SyntaxError: Cannot use import statement outside a module
1 > module.exports = require("react-hook-mousetrap");
I am not sure what this means? I then thought it might be a problem with Nextjs's SSR, since my library enables hotkeys and will use some browser APIs. If you already know that I am on the wrong track here you can stop reading now.
What I did next however was this, I tried dynamic imports:
1. Dynamic import with next/dynamic
First thing I came across was next/dynamic, but this seems to be for JSX / React Components only (correct me if I'm wrong). Here I will be importing and using a React hook.
2. Dynamic import with await (...).default
So I tried dynamically importing it as a module, but I'm not sure how to do this exactly.
I need to use my hook at the top level of my component, can't make that Component async and now don't know what to do?
const MyComponent = () => {
// (1) TRIED THIS:
const useMousetrap = await import("react-hook-mousetrap").default;
//can't use the hook here since my Component is not async; Can't make the Component async, since this breaks stuff
// (2) TRIED THIS:
(async () => {
const useMousetrap = (await import("react-hook-mousetrap")).default;
// in this async function i can't use the hook, because it needs to be called at the top level.
})()
//....
}
Any advice here would be appreciated!
The error occurs because react-hook-mousetrap is exported as an ESM library. You can have Next.js transpile it using next-transpile-modules in your next.config.js.
const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);
module.exports = withTM({ /* Your Next.js config */});
I don't know if my answer is actual, but i'm facing whith this problem today, and what that i done:
//test component for modal
const Button: React.FC<{close?: () => void}> = ({ close }) => (
<React.Fragment>
<button type="button" onClick={ close }>Close</button>
</React.Fragment>
);
// async call import react custom hook in next js whithout a dynamic
//import
let newHook;
(async () => {
const { hookFromNodeModules } =
await import('path/to/hook');
newHook = hookFromNodeModules;
})();
export default function Home() {
// check if hook is available
const openModal = newHook && newHook();
const { t } = useTranslation('common');
// useCallback for update call function when hook is available
const handleOpen = React.useCallback(() => {
openModal?.openModal(Button, {});
}, [openModal]);
return ( ...your code )
}
hope this help!)
screen from next.js app

Exporting multiple functions with module.exports in ES6

I'm building a node.js application and I'm trying to put all my mongodb logic in a seperate file. At this time this file only has one function to initialize the mongodb connection. I want to export all the functions from this file using module.exports.
My mongo file looks as follows:
import { connect } from "mongoose";
const run = async (db: string): Promise<void> => {
await connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
};
module.exports = {
run
};
I want to use this run function in index.ts and im trying to import it as an ES6 module but I can't get it working with the above code.
How I'm importing:
index.ts:
import * as mongo from "./mongo";
Trying to call my run method:
mongo.run('dburl');
This throws following error: 'property run does not exist'
Now I have found a solution to this problem by adding an extra export before my run declaration:
export const run = async (db: string): Promise<void> => {...}
I don't understand why I have to do this as I'm already exporting this function inside module.exports, am I importing it wrong in my index file or is there a better way of doing this?
MDN: JavaScript Modules
There are different types of modules in JS.
ES6 Modules use the export keyword. You can import all the exports like this import * as ... from "..." or import individual exports via import { ... } from "..."
CommonJS modules use modules.exports which is equivalent to export default in ES6 modules. These you can import like this import ... from "...".
So when you use modules.exports you would either have to change your import to:
const mongo = require('./mongo');
Or you could change your export to:
export { run }

Exporting a dynamic import

I'd like to export a different package from a custom module based on an expression
const settings = {}
const init = (sentry) => {
sentry.init(settings)
return sentry
}
const pkg = async () => {
let mod
if (__CLIENT__) {
mod = await import('#sentry/browser').then(init)
} else {
mod = await import('#sentry/node').then(init)
}
return mod
}
const Sentry = pkg()
console.log({ Sentry })
export default Sentry
However, when i import this file later i receive a pending promise
import Sentry from 'config/sentry'
console.log(Sentry) // -> promise pending
Is it possible to default export the dynamically imported module at the top level?
update
I ended up going with require instead of dynamic imports, as supported by webpack globals setup on my system
const Sentry = __CLIENT__ ? require('#sentry/browser') : require('#sentry/node')
Async functions always return a promise. That's by definition. Since dynamic imports also return promises (and are async), you can't export them, since exports have to be at the top level of a script. The best you can do is export the promise and include a .then handler in whichever script imports it; since you're returning mod from your async function, that will be passed to the .then handler's parameter for you to use there.

Can ES6 imports be awaited?

I saw this answer about differences between es6 imports vs require.
But one of the answers there caught my eyes:
Thing is import() is actually async in nature.
Example :
const module = await import('./module.js');
mdn says nothing about it.
I've been using imports for some time now but never knew that it can be awaited ??
I've also created an experiment (dummy angular test):
1.ts
export const a=3;
app.component.ts
import { Component } from '#angular/core'; //no await here
#Component({
...
})
export class AppComponent {
constructor() {
this.foo();
}
async foo() {
const module = await import('./1'); //<--- if I remove the await, it doesn't work
alerqt(module.a)
}
}
So it seems that import returns a promise ?
Question
What am I missing? I didn't have to await in the first two lines of where I imported Component:
import { Component } from '#angular/core'; //no await
#Component({
...
})
And where does it say that import returns a promise ?
Also , one of the webpack programmers : (or system.js) said :
If import was just an asynchronous function, then it would no longer
be possible to statically analyze modules, as just like CommonJS
require, I could have import within arbitrary conditions etc.
But from my testing it does require await , which makes it asynchronisly evaluated.
So what is going on here?

How can I conditionally import an ES6 module?

I need to do something like:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
The above code does not compile; it throws SyntaxError: ... 'import' and 'export' may only appear at the top level.
I tried using System.import as shown here, but I don't know where System comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a deprecated docs page.
We do have dynamic imports proposal now with ECMA. This is in stage 3. This is also available as babel-preset.
Following is way to do conditional rendering as per your case.
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
This basically returns a promise. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.
If you'd like, you could use require. This is a way to have a conditional require statement.
let something = null;
let other = null;
if (condition) {
something = require('something');
other = require('something').other;
}
if (something && other) {
something.doStuff();
other.doOtherStuff();
}
You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.
You can do:
api.js
import mockAPI from './mockAPI'
import realAPI from './realAPI'
const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI
apiConsumer.js
import API from './api'
...
I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.
2020 Update
You can now call the import keyword as a function (i.e. import()) to load a module at runtime. It returns a Promise that resolves to an object with the module exports.
Example:
const mymodule = await import('modulename');
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
or:
import('modulename')
.then(mymodule => {
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
});
See Dynamic Imports on MDN
Looks like the answer is that, as of now, you can't.
http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api
I think the intent is to enable static analysis as much as possible, and conditionally imported modules break that. Also worth mentioning -- I'm using Babel, and I'm guessing that System is not supported by Babel because the module loader API didn't become an ES6 standard.
Import and Export Conditionally in JS
const value = (
await import(`${condtion ? `./file1.js` : `./file2.js`}`)
).default
export default value
Important difference if you use dynamic import Webpack mode eager:
if (normalCondition) {
// this will be included to bundle, whether you use it or not
import(...);
}
if (process.env.SOMETHING === 'true') {
// this will not be included to bundle, if SOMETHING is not 'true'
import(...);
}
require() is a way to import some module on the run time and it equally qualifies for static analysis like import if used with string literal paths. This is required by bundler to pick dependencies for the bundle.
const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;
For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.
// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';
// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);
obscuring it in an eval worked for me, hiding it from the static analyzer ...
if (typeof __CLI__ !== 'undefined') {
eval("require('fs');")
}
Conditional imports could also be achieved with a ternary and require()s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
I was able to achieve this using an immediately-invoked function and require statement.
const something = (() => (
condition ? require('something') : null
))();
if(something) {
something.doStuff();
}
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
JavaScript modules Github
Javascript Modules MDN
No, you can't!
However, having bumped into that issue should make you rethink on how you organize your code.
Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/
I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.
One can go through the below link to learn more about dynamic imports
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
I know this is not what the question is asking for, but here is my approach to use mocks when using vite. I'm sure we can do the same with webpack and others.
Suppose we have two libraries with same interface: link.js and link-mock.js, then:
In my vite.config.js
export default defineConfig(({ command, mode }) => {
const cfg = {/* ... */}
if (process.env.VITE_MOCK == 1) {
cfg.resolve.alias["./link"] = "./link-mock"; // magic is here!
}
return cfg;
}
code:
import { link } from "./link";
in console we call:
# to use the real link.js
npm run vite
# to use the mock link-mock.js
VITE_MOCK=1 npm run vite
or
package.json script
{
....
"scripts": {
"dev": "vite",
"dev-mock": "VITE_MOCK=1 vite"
}
}

Categories