Curry.js error when exporting a rescript function with more than 1 parameter using genType - node.js

When exporting a function with more than 1 parameter (2 or more) it throws the following error, which basically says there is an issue with the way we import curry.js. I am attaching an example and package versions below.
Error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: path/to/node_modules/rescript/lib/es6/curry.js
require() of ES modules is not supported.
require() of /path/to/node_modules/rescript/lib/es6/curry.js from /path/to/src/demo.gen.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename curry.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /path/to/node_modules/rescript/lib/es6/package.json.
at new NodeError (node:internal/errors:329:5)
at Module._extensions..js (node:internal/modules/cjs/loader:1109:13)
at Object.require.extensions.<computed> [as .js] (/path/to/node_modules/ts-node/src/index.ts:851:44)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/path/to/src/demo.gen.ts:6:1)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Module.m._compile (/path/to/node_modules/ts-node/src/index.ts:858:23)
Example
demo.res
#genType
let helloWord = (firstName: string, lastName: string): unit => {
Js.log("Hello " ++ firstName ++ " " ++ lastName)
}
demo.bs.js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
function helloWord(firstName, lastName) {
console.log("Hello " + firstName + " " + lastName);
}
exports.helloWord = helloWord;
/* No side effect */
demo.gen.ts
/* TypeScript file generated from demo.res by genType. */
/* eslint-disable import/first */
// #ts-ignore: Implicit any on import
import * as Curry__Es6Import from 'rescript/lib/es6/curry.js';
const Curry: any = Curry__Es6Import;
// #ts-ignore: Implicit any on import
import * as demoBS__Es6Import from './demo.bs';
const demoBS: any = demoBS__Es6Import;
export const helloWord: (firstName:string, lastName:string) => void = function (Arg1: any, Arg2: any) {
const result = Curry._2(demoBS.helloWord, Arg1, Arg2);
return result
};
package.json
{
"ts-node": "^10.2.1",
"gentype": "^4.1.0",
"rescript": "^9.1.4",
"typescript": "^3.9.6"
}
Node Version
$ node -v
v15.11.0
OS
Manjaro Linux

After taking a look at this file in genType: https://github.com/rescript-association/genType/blob/fb6201266558a64d62441f7ac0d8d6652456397a/src/Config_.ml
I found this option
{
"gentypeconfig": {
"module": "commonjs",
}
}
setting that solves the issue :D
I could not found it anywhere else in rescript docs unfortunately :(

Related

Can't import object from local types package?

I have an issue where I am trying to import an object from a types package in my project, built with yarn work spaces and Turbo-repo. But I am unable to because I get this error.
import {Injectable} from "#nestjs/common"
import {SAMPLE_SONG_INFO, Song} from "types"
#Injectable()
export class CurrentSongService {
private currentSong: Song = SAMPLE_SONG_INFO
get() {
return this.currentSong
}
set(song: Song) {
this.currentSong = song
}
}
I import it with "types": "*", in package.json. I have no project references setup in tsconfig.json
A brief overview of types file:
const SAMPLE_SONG_INFO: Song = {
name: "While My Guitar Gently Weeps",
album: "The Beatles",
artist: "The Beatles",
imageUrl: "sample-album-cover.jpeg"
}
interface Song {
name: string
album: string
artist: string
imageUrl: string
}
export type {Song}
export {SAMPLE_SONG_INFO}
When I run the application the error I get is:
const SAMPLE_SONG_INFO: Song = {
^^^^^^^^^^^^^^^^
SyntaxError: Missing initializer in const declaration
at compileFunction (<anonymous>)
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/media/joshua/379a09fe-3da5-4787-9a8c-cb522be8375d/code/personal/music-circle/apps/api/src/websockets/current-song/current-song.service.ts:2:1)
I run the program with NestJS run dev.
In NextJS I fixed this with next-transpile-modules.
Any help would be appreciated.
Thanks.

How to use nanoid without import

I am stuck with an issue,
I have to generate a 6 digit alphanumeric CODE which should be unique and for that i am using nanoid,
Now when i code this:
const {nanoid} = require("nanoid");
const ID = nanoid();
I got error:
const {nanoid} = require("nanoid");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\HP\Desktop\test\node_modules\nanoid\index.js from C:\Users\HP\Desktop\test\server.js not supported.
Instead change the require of index.js in C:\Users\HP\Desktop\test\server.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\Users\HP\Desktop\test\server.js:1:18) {
code: ←[32m'ERR_REQUIRE_ESM'←[39m
}
if I code this:
import { nanoid } from 'nanoid'
const id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
i got error:
(node:4636) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\HP\Desktop\test\server.js:4
import { nanoid } from 'nanoid'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Now I have tried changing package.json file
"type":"module"
but my project use babel and it will automatically convert import to require and as result first error come again.
could you please tell me how to do nanoid with require'
Thank you
This is a feature, not a bug. See the changelog for details of the breaking change in version 4.0
https://github.com/ai/nanoid/issues/365

Cannot read property 'jquery' of undefined

I have a Rails 6 application with Webpacker. Node packages have been successfully installed with yarn.
The application works locally both in development and production modes with Puma server. But when calling the website on our virtual host, Phusion Passenger fails loading the Bootstrap 4 JavaScript part:
/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:21178
var e = i.default.fn.jquery.split(' ')[0].split('.');
^
TypeError: Cannot read property 'jquery' of undefined
at Object.jQueryDetection (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:21178:32)
at a (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:21183:9)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:22435:56)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
at Module.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:18176:7)
at Module.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:18179:7)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
at /var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:26:98
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:27:2)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
app/javascript/packs/application.js:
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
console.log('Webpacker: START application.js');
require('#rails/ujs').start();
require('turbolinks').start();
require('#rails/activestorage').start();
require('channels');
require('jquery');
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
// #################### Proprietary configuration ####################
// JAVASCRIPT LIBRARIES
import 'popper.js';
import 'bootstrap';
import '#fortawesome/fontawesome-free';
// CSS OF USED LIBRARIES
import 'stylesheets/application';
// datetime picker
// load "moment" globally to avoid:
// "Error: Tempus Dominus Bootstrap4's requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4's JavaScript."
// See https://stackoverflow.com/questions/49580266/tempus-dominus-bootstrap4-requires-moment-js-datetime-picker
global.moment = require('moment');
require('moment/locale/de');
// If you require timezone data (see moment-timezone-rails for additional file options)
// import "moment-timezone-with-data"
require('tempusdominus-bootstrap-4');
console.log('Webpacker: END application.js');
config/webpack/environments.js (don't know what's correct here):
const { environment } = require('#rails/webpacker')
const webpack = require('webpack');
environment.plugins.prepend('Provide', // append
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery' // ,
// Popper: ['popper.js', 'defaults']
})
);
module.exports = environment
package.json:
{
"name": "myapp",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-free": "^5.15.4",
"#popperjs/core": "^2.10.1",
"#rails/activestorage": "^6.1.4-1",
"#rails/ujs": "^6.1.4-1",
"#rails/webpacker": "5.4.3",
"bootstrap": "4.6.0",
"jquery": "^3.6.0",
"moment": "^2.29.1",
"moment-timezone": "^0.5.33",
"popper.js": "^1.16.1",
"tempusdominus-bootstrap-4": "^5.39.0",
"tempusdominus-core": "^5.19.0",
"turbolinks": "^5.2.0",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12"
},
"devDependencies": {
"webpack-dev-server": "^3"
}
}
When I use
if (typeof window !== "undefined") {
require('popper.js');
require('bootstrap');
require('#fortawesome/fontawesome-free');
}
like in Trying to import Bootstrap on Next.JS but says "TypeError: Cannot read property 'jquery' of undefined", I get another error:
/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1785
return window.document;
^
ReferenceError: window is not defined
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1785:7)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1786:7)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:6524:10)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1682:110)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1772:8)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
at Object.<anonymous> (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:1860:7)
at n (/var/www/vhosts/mydomain.com/httpdocs/myapp/public/packs/js/application-2432a12b5b63094eb637.js:8:17)
What am I missing?
Rails applications with Webpacker must not run as Node.js application additionally, although there are some Node packages used with Webpacker. They are only for client-side.
Phusion Passenger on the virtual host was configured not to load frequent application changes of all my numerous trial fixes. That's why the error didn't disappear when I tried the above solution weeks ago already ;-)
https://stackoverflow.com/questions/60198141/trying-to-import-bootstrap-on-next-js-but-says-typeerror-cannot-read-property was correct. Just had to wrap ALL Javascript library loads in application.js into condition:
if (typeof window !== "undefined")

Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless

I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console.
One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues.
This is the sample code which is throwing error
const { IamAuthenticator } = require('ibm-watson/auth');
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
async function textAnalyse(req, res) {
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2019-07-12',
authenticator: new IamAuthenticator({
apikey: 'API KEY'
}),
url: 'https://URL/natural-language-understanding/api'
});
const analyzeParams = {
'text': HtmlToText.fromString('Test text here'),
'features': {
'entities': {
'sentiment': true,
'limit': 100
}
}
};
const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);
// prepare the response object
res.send({ analysis: analysis });
}
Error in AWS Cloud watch
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'axios/lib/utils'",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:45:30)",
" at Module._compile (internal/modules/cjs/loader.js:778:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
" at Module.load (internal/modules/cjs/loader.js:653:32)",
" at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
" at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
" at startup (internal/bootstrap/node.js:283:19)",
" at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"
]
}
I found the fixes for this.
when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency
"dependencies": {
"axios": "^0.19.2"
}
Then add the layer in the functions from AWS UI, left side menu
Then add the layer to your function
Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.
Also, what you name the folders matters before zipping. Review these AWS docs for folder naming so you can import the library like you would in any other project.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

Enabling ECMAScript modules in Node.js [duplicate]

This question already has answers here:
Node.js - SyntaxError: Unexpected token import
(16 answers)
Closed 3 years ago.
I'm experimenting with ECMAScript modules in Node.js 12 but I'm struggling with. Following the official docs just by adding the top-level field "type" with a value of "module" it should be enough to keep using the extension .js in this Node.js version but I can not find why is not working as expected. Am I missing something?
$ node --version
v12.14.1
$ cat package.json
{
"type": "module",
"scripts": {
"start": "node test.js"
}
}
$ npm start
> app# start /usr/src/app
> node test.js
/usr/src/app/test.js:1
import { myFunction } from './module.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
$ cat test.js
import { myFunction } from './module.js';
myFunction();
$ cat module.js
function myFunction() {
console.log('hello from module');
}
export { myFunction };
https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_code_import_code_statements
Version 12 docs for that import statement show that you can only import the default export via import ... from ...
So import myFunction from './module.js'; would work if you exported myFunction as export default myFunction;

Resources