I am getting this error and don't know how to resolve it - node.js

index.ts:5:8 - error TS1192: Module '"D:/Calculator/node_modules/#types/chalk-animation/index"' has no default export.
5 import chalkAnimation from "chalk-animation";
~~~~~~
index.ts:22:1 - error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
22 await welcome()
I am trying to use inquirer,chalk and chalk animation in node.js .Although my calculator is running on other computer but I don't understand why it is showing this error in my computer

In your tsconfig.json file, under "compilerOptions", add "esModuleInterop": true.
{
...
"compilerOptions": {
...
"esModuleInterop": true,
...
},
...
}
Without esModuleInterop, TypeScript defaults to resolving import names with a legacy mechanism, that is not compliant with the ESM spec, and is not compatible with the way Node.js handles imports of CJS modules in new code.

Related

Mongoose Schema pagination typing using mongoose-paginate-ts

EDIT FIXED :
What I onited say in my initial post is that I was exporting the mongoose-pagination-ts function & interface from a global file, and then importing it in my schema files to use it. However, it appears that I need to import the module directly in each schema file in order for it to work, Interface cannot be export in a file and import in another, comming from a node_module in CommonJS (Apparently, not sure if it's the correct reason)
I'm facing the following issue :
The module mongoose-pagination-ts explains as follow :
import { mongoosePagination, Pagination } from "mongoose-paginate-ts";
type User = mongoose.Document & {
username: String,
accounts: [mongoose.Types.ObjectId]
};
const userSchema = new Schema({
username: String,
accounts: [{ type: ObjectId, ref: "Account" }]
});
userSchema.plugin(mongoosePagination);
const User: Pagination<User> = mongoose.model<User, Pagination<User>>("User", userSchema);
//User.paginate()
The build passes with no issue, but when I execute the server in development mode using the following command I have the bellow issue :
nodemon --ext 'ts,js,cjs,json' --ignore 'tests/' --exec 'ts-node-esm src/index.ts'
import { mongoosePagination, Pagination } from "mongoose-paginate-ts";
^^^^^^^^^^
SyntaxError: Named export 'Pagination' not found. The requested module 'mongoose-paginate-ts' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'mongoose-paginate-ts';
const { mongoosePagination, Pagination } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:190:5)
tsconfig.js
{
"compilerOptions": {
"experimentalDecorators": true,
"target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"module": "ESNext" /* Specify what module code is generated. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
"moduleResolution": "NodeNext" /* Specify how TypeScript looks up a file from a given module specifier. */,
"baseUrl": "./src" /* Specify the base directory to resolve non-relative module names. */,
"outDir": "build",
"types": ["node", "mocha"] /* Specify type package names to be included without being referenced in a source file. */,
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */,
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"strict": false /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
"resolveJsonModule": true
},
"ts-node": {
"swc": true
},
"exclude": ["tests", "node_modules"]
}
Any solution is welcomed, thanks !
The error is clear : the module is exported as a CommonJS module and the proposed solution should work, however, the Pagination interface cannot be destructured as explained :
import pkg from 'mongoose-paginate-ts';
const { mongoosePagination, Pagination } = pkg; // Pagination is not found

rollup.js: crypto.getRandomValues() not supported

I am working on an Obsidian plugin that requires bundling using rollup.js. This plugin needs to import inrupt solid libraries that, when imported, are causing the following error:
Error: crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported
at rng (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:16740:10)
at v4 (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:17186:53)
at new Session (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23526:88)
at Repro.<anonymous> (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23669:17)
at step (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:160:15)
at Object.next (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:111:11)
at /Users/candide/work/sekund/solid-build-issues/main_rollup.js:83:65
at new Promise (<anonymous>)
at __awaiter (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:65:9)
at Repro.login (/Users/candide/work/sekund/solid-build-issues/main_rollup.js:23664:10)
When debugging the code, it turns out that the crypto constant is not defined. However, at the start of the generated bundle, I can see:
var crypto_1 = require("crypto");
So it looks like my problem basically boils down to rollup redefining global variables when it should not.
Indeed, using the typescript compiler (tsc) on the same source file outputs a perfectly working program.
Here's my rollup config:
import commonjs from "#rollup/plugin-commonjs";
import json from "#rollup/plugin-json";
import { nodeResolve } from "#rollup/plugin-node-resolve";
import typescript from "#rollup/plugin-typescript";
const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/
`;
export default {
input: "src/main.ts",
inlineDynamicImports: true,
output: [
{
file: "main.js",
sourcemap: "inline",
format: "cjs",
exports: "default",
banner,
},
],
external: ["obsidian", "fs", "os", "path"],
plugins: [json(), nodeResolve({ preferBuiltins: true }), commonjs(), typescript({ sourceMap: true })],
};
I created a repro repo at https://github.com/ckemmler/solid-build-issues
man this wrecked my brain for a bit, i managed to find a solution but i don't understand it 100%
please see the solution suggested in this comment https://github.com/uuidjs/uuid/issues/544#issuecomment-740394448
resolved the problem for me

TypeScript on AWS Lambda: to bundle imports (how?) or not to bundle? or: Runtime.ImportModuleError: Cannot find module '#aws-sdk/..."

I have the following lambda.ts code I'm trying to make running on an AWS Lambda:
import 'aws-sdk'
import { /* bunch of stuff... */ } from "#aws-sdk/client-cloudwatch-logs";
import {Context, APIGatewayProxyResult} from 'aws-lambda';
import {DateTime} from "luxon";
export const lambdaHandler = async (event: any, context: Context): Promise<APIGatewayProxyResult> => {
/* ... stuff ... */
}
which gets transpiled to:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.lambdaHandler = void 0;
require("aws-sdk");
//import {CloudWatchClient} from "#aws-sdk/client-cloudwatch";
const client_cloudwatch_logs_1 = require("#aws-sdk/client-cloudwatch-logs");
const luxon_1 = require("luxon");
const lambdaHandler = async (event, context) => {
/* ... transpiled stuff ... */
}
When hitting the button, I'm getting this Response:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module '#aws-sdk/client-cloudwatch-logs'\nRequire stack:\n- /var/task/lambda.js\n- /var/runtime/index.mjs",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module '#aws-sdk/client-cloudwatch-logs'",
"Require stack:",
"- /var/task/lambda.js",
"- /var/runtime/index.mjs",
" at _loadUserApp (file:///var/runtime/index.mjs:951:17)",
" at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:976:21)",
" at async start (file:///var/runtime/index.mjs:1137:23)",
" at async file:///var/runtime/index.mjs:1143:1"
]
}
I played a lot with tsconfig.json, trying many things from Google / GitHub / SO / Rumors / Astrology / Numerology / Praying (monotheistic, pantheon-dwelling, neither..), but it only made me more confused.
For instance:
Using the tsconfig.json from Building Lambda functions with TypeScript still emits a single transpiled .js file without embedding the imported #aws-sdk/client-cloudwatch-logs module in the emitted output lambda.js file
Installing the AWS Common Runtime (CRT) Dependency
states that I need to npm install #aws-sdk/... (naturally), but doesn't explain anything beyond, which makes me think that maybe I shouldn't bundle them at all, but simply import them (in the assumption that they are pre-defined/loaded in AWS's Lambda's runtime)
Runtime is Node.js 16.x, Handler is lambda.lambdaHandler (emitted file is called lambda.js), and this is my current tsconfig.json:
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "Node",
"target": "ES2022",
"sourceMap": true,
"lib": [
"ES2021"
],
"typeRoots": ["node_modules/#types"],
"outDir": "build",
"baseUrl": "src",
"strict": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"inlineSources": true,
"rootDir": "src",
"preserveConstEnums": true,
"isolatedModules": true,
"incremental": true,
"importHelpers": true
},
"exclude": [
"node_modules",
"**/*.test.ts"
]
}
So I'm trying to understand:
Do I even need to bundle those imported modules (such as #aws-sdk/client-cloudwatch-logs) at all, or they are already loaded by AWS Lambda's runtime?
If I do need to bundle, then how? do I need to use some bundler or is it just a matter of configuring tsconfig.json properly?
If bundler isn't mandatory, then how do I setup tsconfig.json to emit those 3rd-party modules?
If a bundler is mandatory, then can they all fit (WebPack, Babel, etc..)? or since no frontend (index.html) is involved, then not all of them can fit?
AWS SDK for JavaScript v3 (AKA modular) is not installed globally in the lambda execution context. You are using a v3 module (#aws-sdk/client-cloudwatch-logs) which is why it fails. AWS SDK v2 is installed globally, you are also using it (aws-sdk) so that require works fine.
You should use a bundler like webpack, esbuild, parcel or rollup. If you are using AWS CDK, there is a nodejs function construct that will do the bundling with esbuild for you.
TS will only emit your compiled javascript. If you are depending on javascript found in your node_modules directory, simply include that directory in your deployment package.
Generally, bundlers will take your application entry points (main.js, handler.js, whatever you want really) and recursively resolve all the dependencies, tree-shake any unreachable code then create one file for each entry point that has no other external dependencies. There is a runtime performance cost to this of course but it does simplify things and in a serverless context it isn't usually too impactful.
So, to resolve your error you can take one of two approaches:
Include your node_modules directory in your deployment package. (trivial)
Use a bundler or CDK (more complex)
Note that in either case, you need to be careful about dependencies with native bindings (binaries basically) as the one installed on your dev machine likely isn't supported in the lambda environment.

How to pass separate TypeScript config for TSNode when it has being indecency running by Mocha & IntellIJ IDEA?

Although TS-Node started the ECMAScript modules support, it has a lot of limitations and below example:
import { assert as Assert } from "chai";
describe("firstTest", (): void => {
it("", (): void => {
Assert.isTrue(true);
});
});
does not work with next settings:
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"strict": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"baseUrl": "./",
"paths": {},
"noUnusedParameters": true,
"noImplicitReturns": true
}
}
.mocharc.yaml
extension:
- ts
spec: "**/*.test.ts"
require:
- ts-node/register
- tsconfig-paths/register
Error:
import { assert as Assert } from "chai";
^^^^^^
SyntaxError: Cannot use import statement outside a module
I need the ECMAScript modules because the Webpack dynamic loading does not work with CommonJS modules. So the conceptual solution is create the additional tsconfig.json for TSNode or pass modules type via console. It's has been documented how to do it for TSNode, but here I don't execute TSNode directly - I launch the Mocha via IntelliJ IDEA:
IntelliJ IDEA and, I suppose, all IDEs of this family including WebStorm generates the below command (added the line breaks):
"C:\Program Files\nodejs\node.exe"
"D:\XXX\MyProject\node_modules\mocha\bin\mocha" --require ts-node/register --ui bdd --reporter C:\Users\XXX\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\203.7148.57\plugins\NodeJS\js\mocha-intellij\lib\mochaIntellijReporter.js
"D:\XXX\MyProject\Test\Test.test.ts" --grep "^firstTest "
Now how to set CommonJS modules type?
According to ts-node's documentation (search for IntelliJ), you can create an alternative tsconfig.json (containing the option "module": "CommonJS") and enforce it for Mocha tests using environment variable TS_NODE_PROJECT. In the configuration corresponding to your Mocha testing, in the Environment variables section, you set this variable to the pathname of this alternative tsconfig.json. Note, multiple tsconfig.json files can use one common "base" file and extend/partially override it (see).

TypeScript AMD compilation and "barrel" modules

I'm trying to set up a Node.js + TypeScript project using Intern for testing. Everything works fine when I compile the project using "commonjs" (which I do for the normal build); and TypeScript is equally happy when compiling for "amd", which is required by Intern. However, when passing the tests with intern-client, it complains about a couple of things:
First, imports from "index.ts" files (so-called "barrel" modules) won't work. My setup is something like this (everything in the same directory):
// index.ts
export { x } from './x'
// x.ts
export function x() {}
// x.test.ts
import { x } from '.' // "Error: Failed to load module ..."
In fact, the generated JavaScript code (for x.test.ts) looks something like this:
define(["require", "exports", "."], function (...) { ... })
And I'm not sure that AMD knows how to handle the ".".
The second issue happens under the same circumstances (TypeScript compiles happily, but intern-client complains). In summary, I get an error when doing:
import jsdom = require('jsdom')
Which I need to transform to:
const jsdom = require('jsdom')
For Intern to be able to deal with it.
Here is the tsconfig.json file I use to compile the tests:
{
"compilerOptions": {
"target": "es6",
"module": "amd",
"moduleResolution": "node",
"sourceMap": true,
"rootDir": "src",
"outDir": "build/tests",
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
And here is my intern.js configuration file, in case it helps:
define({
suites: ['build/tests/**/*.test.js'],
excludeInstrumentation: true,
filterErrorStack: true
})
Edit (2017-05-03)
To help understand the issue, here is an excerpt of the directory tree of the project:
build
tests // The compiled tests will end up here
src
core
utils
x.ts
x.test.ts
// Other files, each containing a function that I would like to unit-test...
intern.js
package.json
tsconfig.json
...
Regarding the first issue, AMD's handling of an import like '.' is different than Node's. While both of them will map '.' to a package, Node uses a default module name of index.js, while AMD uses main.js. To get things working in an AMD loader, you'll need to first define a package for '.', and then tell the AMD loader what default module to use for that package. Given your project layout, you could configure Intern like this:
loaderOptions: {
map: {
// When a module in src/ references 'src/utils', redirect
// it to 'utils'
'src': {
'src/utils': 'utils'
}
},
packages: [
// Define a package 'utils' with files in 'src/utils' that defaults
// to the module index.js
{ name: 'utils', location: 'src/utils', main: 'index.js' }
]
}
Regarding the second issue, its not clear what the problem actually is. Import statements will be transpiled into define dependencies by TypeScript, so Intern should never be seeing them.

Resources