How to export a function in nodejs that I made - javascript

Every time I try to import into my nodejs file I get the error, cannot import outside a module
I have tried multiple solutions on StackOverFlow such as adding
"type":"module"
and setting file extensions to .mjs
I want to import constants from a different file but I am not sure how to
example
functions.js
export const myFunc = (param1) => return 'hello'
backend.js
import {myFun} from './.js'
How should I import them?
Sorry I accessed a similar question for constants but the same method does not work for functions

First, "type": "module" needs to be in the package.json or both JS files need to end in .mjs. You seem to be aware of this, but just making sure as the filenames you have provided don't end in .mjs, and you haven't provided your package.json.
When using arrow functions, the return is implied. If you try to use return in an arrow function, an error will occur. Also, in backend.js, you are importing myFun, which is not in functions.js. I believe you meant to import myFunc.
functions.mjs
export const myFunc = (param1) => "hello"
backend.mjs
import { myFunc } from './functions.mjs'
console.log(myFunc("test"))

Related

How to import a file that already imports another file?

Javascript, ES6. I have three files:
inline-functions.js
\*
Bunch of small functions.
*/
some-module.js
import './inline-functions.js'
// uses many inline functions
main.js
import './inline-functions.js'
import './some-module.js'
// uses inline functions as well as classes from some-module.js
Now, I use Visual Studio Code and I would like Intellisense working but when I am editing main.js, it only shows functions from inline-functions.js and everything from 'some-module.js' is unreachable even though there is an import statement. However, when I comment the import out of some-module.js like this:
// import './inline-functions.js'
// tries to use inline functions which are now not callable
Intellisense suddenly shows correct names and documentation for all objects. This is of course unusable because some-module.js now can't call any of the inline functions.
What is the correct way of importing these modules?
You can access the module function only if you export it from the module.
Export the function form the module then you will see it in main js.
Example:
some-module.js
import './inline-functions.js'
const someFuncion1 = () => 1;
const someFuncion2 = () => 2;
export {
someFuncion1,
someFuncion2
}
main.js
import * as inline './inline-functions.js'
import * as some './some-module.js'
//Access it like
inline.<function name>
some.<function name>

Import, rename, and export a function in JavaScript?

With JavaScript what's the shortest way to import a named export, rename it, and export it again?
This code works but it feels more verbose than it should be
import { mock as myFunctionMock } from 'context/myFunction';
export const myFunction = myFunctionMock;
You can combine the import and export like so:
export { mock as myFunctionMock } from 'context/myFunction';
See MDN Docs
Note that you won't actually be able to use myFunctionMock within your code file since you haven't imported it. Neither mock nor myFunctionMock will be defined within this module.
This is a useful shorthand when you're building a library that will be used by other modules or by your end-user.
For example, if you had a utils library that you wanted to export, but you wanted to organize your util functions across several smaller files, such as stringUtils, objectUtils, dataUtils, etc, you can export the contents of those modules within your utils module to create a single, monolithic access point:
stringUtils.js
export function toLower(){}
export function toUpper(){}
objectUtils.js
export function propertyMap(){}
utils.js
export {
toLower as stringToLower,
toUpper as stringToUpper,
} from "stringUtils.js";
export {
propertyMap as objectPropertyMap
} from "objectUtils.js";
I wouldn't generally recommend this approach for internal code as it can make your dependency trees a bit wonky in some cases. It can, however, be extremely useful in situations where you want to import from a common interface but the implementation is dependent on the build (prod vs dev, web vs node, etc)
import { mock as myFunction } from 'context/myFunction';
export { myFunction };
in your original exporter, do:
module.exports = { mock: function () {...}}
When importing, do:
const myFunctionMock = require('file path of exporter');
then to reexport in the same file:
module.exports = {renamedMock: myFunctionMock};
Now any changes to mock will propagate to the other modules where it's referenced (side note, this is node.js in a nutshell).

Import JS web assembly into TypeScript

I'm trying to use wasm-clingo in my TypeScript React project. I tried to write my own d.ts file for the project:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
export const Module: any;
}
and import like this:
import { Module } from 'wasm-clingo';
but when I console.log(Module) it says undefined. What did I do wrong?
Notes:
clingo.js is the main js file.
index.html and index_amd.html are two example pages
Solution:
I solved the problem like this:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
const Clingo: (Module: any) => Promise<any>;
namespace Clingo {}
export = Clingo;
}
and
import * as Clingo from 'wasm-clingo';
Here's the source for this solution
I know you found a solution acceptable to you; however, you don't really have any types here, you just have Module declared as any, which gives you no typescript benefits at all. In a similar situation I used #types/emscripten, which provides full type definitions for web assembly modules compiled using emscripten. You simply need to do:
npm install --save-dev #types/emscripten
then change your tsconfig.json types array to add an entry for emscripten.
After that you can just write Module.ccall(...) etc. If you like you could of course write const Clingo = Module and then make calls against that if you want a more descriptive name than Module (which is a terrible name!).
You're welcome ;)
I think the issue is that wasm-clingo exports the module itself but import { Module } from 'wasm-clingo' expects a property.
Try
import Clingo_ from 'wasm-clingo';
const Clingo: typeof Clingo_ = (Clingo_ as any).default || Clingo_;

Make package available from browser and as npm package

I have main.js and two function on this file to export, like:
export function one() {}
export function two() {}
Next, I imported functions to index.js, with import:
import { one, two } from './src/main'
And bundled it, with webpack, and used index.js as entry point.
How I can make, to use this script, as npm package, and as CDN from bundled script (or just local connect from path)?
I found, solution like:
import { one, two } from './src/main'
window.one = one
window.two = two
export { one, two }
But, it's now seems very neat.
Thanks, for your ideas and comments.

In VSCode when exporting functions: "Individual declarations must be all exported or all local"

I recently upgraded to Visual Studio Code 0.5.0 and some new errors cropped up that weren't there before.
I have a bunch of functions that are declared locally and then exported. Since the upgrade, however, hovering over each of the local function names produces the error Individual declarations in merged declaration functionName must be all exported or all local.
This is an example local function that is exported.
var testParamsCreatorUpdater = function (lTestParams, creatorID){
lTestParams.creator = creatorID;
return lTestParams;
};
module.exports.testParamsCreatorUpdater = testParamsCreatorUpdater;
I realize I can change this to...
module.exports.testParamsCreatorUpdater = function (lTestParams, creatorID){
lTestParams.creator = creatorID;
return lTestParams;
};
And prepend module.exports. to every testParamsCreatorUpdater() call.
But why is the first snippet wrong? As I understand it, require() makes everything in the module.exports object available to whatever required it.
I had this issue in Webstorm , I Restarted it and it went away
I think at a JavaScript level it cannot differentiate between:
var testParamsCreatorUpdater = ...
and
module.exports.testParamsCreatorUpdater = ...
as the names are the same. I got the exact same error (leading me to this post) in TypeScript when I tried this:
import { AuditService } from '../services/audit.service';
import { Audit } from '../models/audit.model';
#Component({
selector: 'audit',
templateUrl: './audit.component.html',
})
export class Audit {
constructor(private auditService: AuditService) {
}
}
So TypeScript did not like that I imported a module called Audit and exported a class also called Audit.
You are exporting a variable in this file which is imported in the same file module (locally).
I think it's related to the feature of merged declaration for TypeScript ref. I have not done the detailed research for Typescript but it seems that it can include Javascript in the Typescript file.
I guess the way testParamsCreatorUpdater was declared in the Javascript was detected to be error by VSCode because it thinks the two declarations cannot be merged.
So DuckDuckGo got me here searching for the exact same error, but in 2022. I didn't find the exact reason so posting as an update and for completeness.
import { Something, SomethingElse } from './some/path';
import { ref } from 'vue';
// Many lines of code
function doTheStuff() {
// The declarations were previously just local variables ...
// const Something = ref<Something>();
// const SomethingElse = ref<SomethingElse>();
}
// ... but then I decided to export them and got the error
export const Something = ref<Something>();
export const SomethingElse = ref<SomethingElse>();
You simply can not import Something as a type and then export Something variable as a value of a kind (here a vue reference object). However, you can name a local variable the same name as the type, like I originally had. It is the import/export combination where things got broken. Solution for me was to locally rename the types:
import {
Something as SomethingType,
SomethingElse as SomethingElseType
} from './some/path';
import { ref } from 'vue';
// ...
// No naming conflict anymore
export const Something = ref<SomethingType>();
export const SomethingElse = ref<SomethingElseType>();

Categories

Resources