require() of ES modules is not supported - node.js

I have an issue when I try to run webpack with webpack.config.ts written in typescript and ts-node has "require": ["tsconfig-paths/register"]
// tsconfig.json
{
compilerOptions:{
paths: { /* ----------------- */ }
},
'ts-node':{
"require": ["tsconfig-paths/register"],
"compilerOptions": {
"sourceMap": false,
"module": "commonjs"
}
}
}
when I remove "require": ["tsconfig-paths/register"] from ts-node it runs, but webpack cannot detect aliases.
I already set module: commonjs in my tsconfig.json and removed type: module from my package.json
trace
> webpack
(node:5932) Warning: require() of ES modules is not supported.
require() of /home/node_modules/colorette/index.js from /home/node_modules/webpack-cli/lib/utils/index.js 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 /home/node_modules/colorette/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/node_modules/colorette/package.json.
(node:5932) UnhandledPromiseRejectionWarning: /home/node_modules/colorette/index.js:28
export const options = Object.defineProperty({}, "enabled", {
^^^^^^
SyntaxError: Unexpected token 'export'
at new Script (vm.js:84:7)
at NativeCompileCache._moduleCompile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
at Module._compile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:184:36)
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 Module.require (internal/modules/cjs/loader.js:848:19)
at require (/home/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object.get colors [as colors] (/home/node_modules/webpack-cli/lib/utils/index.js:3:16)
at Object.error (/home/node_modules/webpack-cli/lib/utils/logger.js:5:58)
(node:5932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
`

Related

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

Setting up Typescript with expressjs import error

I have a folder structure as following
src
--/lib
----/errors
------/notFound.ts
in notFound.ts, I'm exporting this class
export abstract class HttpError extends Error {
abstract statusCode: number;
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, HttpError.prototype);
}
abstract serializeErrors(): { message: string; field?: string }[];
}
export class NotFoundError extends HttpError {
statusCode = 404;
constructor() {
super('Route not found');
Object.setPrototypeOf(this, NotFoundError.prototype);
}
serializeErrors() {
return [{ message: 'The requested route is not Found' }];
}
}
Then in TSconfig.json, I have the path parameter set like this
"paths": {
"#/lib/*" : [
"src/lib/*"
],
"#/routes/*": [
"src/routes/*"
],
"*": [
"node_modules/*"
]
},
When i Import NotFoundError as follows, it results in error
import { NotFoundError } from '#/lib/errors/notFound';
Here's the error.
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
at Function.Module._load (internal/modules/cjs/loader.js:745:27)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/home/tuser/Projects/tpro/src/server/express.ts:5:1)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Module._compile (/home/tuser/Projects/tpro/node_modules/source-map-support/source-map-support.js:568:25)
at Module.m._compile (/tmp/ts-node-dev-hook-07042914060113459.js:69:33)
at Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-07042914060113459.js:114:20)
[ERROR] 16:40:04 Error: Cannot find module '#/lib/errors/notFound'
I have also tried imports like these
const { NotFoundError } = require('#/lib/errors/notFound')
const NotFoundError = require('#/lib/errors/notFound')
Both result in same error
What am i missing ?
Sorry, I initially wanted to post a comment but I don't have enough rep; instead, I've expanded what I know into a full answer in hopes it helps.
I've recently gone about with setting up Node + TypeScript + Express. The repo I made and was playing around with initially is here, but note that it's undocumented and the auxiliary configs aren't necessarily up to scratch. Also, apologies if the formatting of this answer is really unorthodox, and I hope linking to personal repos is not looked down on.
I'm uncertain if the paths in the tsconfig.json have anything to do with your issue; I've never used them, so I don't know. I would remove them for now.
As a preface, this is an imperfect solution.
For my Node/TypeScript/Express setup I had to do the following:
Set "type": "module" in package.json
Install required packages: > npm install ts-node ts-loader (I'm unsure if both are necessary, I believe they are though)
Add node --es-module-specifier-resolution=node --loader ts-node/esm ./src/server/express.ts (Presuming that express.ts is your entrypoint) as a command to your package.json and check if it works.
With what I understand, this works by specifically invoking ts-node with esm support, and it seems to work on Node 14 LTS and v16.9.1.
The command is rather hacky and will give you warnings about it being an experimental feature. I couldn't find any other solution for myself when (very stubbornly) using ESModules.
I've also used this command to use Webpack with TypeScript and ESM (that is, having a webpack.ts file with ESM imports) to compile TypeScript src files with ESM, as below (in package.json, from here):
"webpack-examples": "node --es-module-specifier-resolution=node --loader ts-node/esm node_modules/webpack-cli/bin/cli.js --config webpack.examples.ts --mode production",
expressjs doesnt support import statements yet. use require for eg const http = require("http");

Nuxt - Node error when I want to import some packages

I use Nuxt, and sometimes, when I want to use some npm packages, I have this error:
SyntaxError
Unexpected token '<'
The stack:
vm.js:102:7
new Script
internal/modules/cjs/loader.js:1114:10
Module._extensions..js
internal/modules/cjs/loader.js:950:32
Module.load
internal/modules/cjs/loader.js:790:14
Module._load
internal/modules/cjs/loader.js:974:19
Module.require
webpack:/external "vue-typeahead-bootstrap":1:
Object.vue-typeahead-bootstrap
webpack/bootstrap:25:
__webpack_require__
pages/account/tabs/addresses.js:693:81
Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./components/address/form/country.vue?vue&type=script&lang=js&
webpack/bootstrap:25:
I have this error for example on this package: vue-typeahead-bootstrap
If I import the package:
import VueTypeaheadBootstrap from ['vue-typeahead-bootstrap'](https://github.com/mattzollinhofer/vue-typeahead-bootstrap)
export default {
components: { VueTypeaheadBootstrap },
}
It throws the error.
Is it because the package is not supported or something ?
You may try to transpile it. https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-build#transpile
Add the package name like this
{
build: {
transpile: [
({ isServer }) => 'vue-typeahead-bootstrap'
]
}
}
As answered here: https://github.com/mattzollinhofer/vue-typeahead-bootstrap/issues/19#issuecomment-645510809

Starting vue js dev server gives eror: .plugins[0] may only be a two-tuple or three-tuple

I am using Vue CLI version 3 to run a Vue application inside a Docker container. To start the development server, I run:
https://cli.vuejs.org/guide/cli-service.html
This gives the following error:
ERROR Failed to compile with 1 errors 17:05:14
error in ./app/main.js
Module build failed (from ./node_modules/#vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js):
Error: .plugins[0] may only be a two-tuple or three-tuple
at assertPluginItem (/home/src/node_modules/#babel/core/lib/config/validation/option-assertions.js:235:13)
at arr.forEach (/home/src/node_modules/#babel/core/lib/config/validation/option-assertions.js:222:30)
at Array.forEach (<anonymous>)
at assertPluginList (/home/src/node_modules/#babel/core/lib/config/validation/option-assertions.js:222:9)
at Object.keys.forEach.key (/home/src/node_modules/#babel/core/lib/config/validation/options.js:107:5)
at Array.forEach (<anonymous>)
at validateNested (/home/src/node_modules/#babel/core/lib/config/validation/options.js:83:21)
at validate (/home/src/node_modules/#babel/core/lib/config/validation/options.js:74:10)
at file (/home/src/node_modules/#babel/core/lib/config/config-chain.js:174:34)
at cachedFunction (/home/src/node_modules/#babel/core/lib/config/caching.js:33:19)
at buildRootChain (/home/src/node_modules/#babel/core/lib/config/config-chain.js:120:36)
at loadPrivatePartialConfig (/home/src/node_modules/#babel/core/lib/config/partial.js:85:55)
at Object.loadPartialConfig (/home/src/node_modules/#babel/core/lib/config/partial.js:110:18)
at Object.<anonymous> (/home/src/node_modules/#vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js:140:26)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/home/src/node_modules/#vue/cli-plugin-babel/node_modules/babel-loader/lib/index.js:3:103)
# multi (webpack)-dev-server/client/index.js ./node_modules/#vue/cli-service/node_modules/webpack/hot/dev-server.js ./app/main.js
I suspect that the offending code is the following, in my .babelrc file:
"plugins": [
["transform-runtime", "transform-vue-jsx", "transform-regenerator", {
"polyfill": false,
"regenerator": true
}]
Could someone suggest how I could go about resolving this? Thanks!
Your [ is in the wrong place. It should be
"plugins": [
"transform-runtime",
"transform-vue-jsx",
["transform-regenerator", {
"polyfill": false,
"regenerator": true
}]
]

Typescript with async/await, Promise and function default parameters

I have a nodeJS-Express-Typescript project where I want to use some native promises with async/await and also some default value for a function. This would be a simple example of what I can achieve:
sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, 500));
}
async someFunction(param = "default") {
doStuff(param);
await sleep(500);
doSomeMoreStuff();
}
The IDE warns me about this error:
$ tsc -p .
error TS2468: Cannot find global value 'Promise'.
spec/routes/users.spec.ts(508,23): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
src/utils/sleep.ts(10,20): error TS2693: 'Promise' only refers to a type, but is being used as a value here.
so I have to add es2015 as target in my tsconfig.json:
"target": "es2015"
But then, this error comes when executing the transpiled JS:
/../users-api/dist/src/repository/realm-helper.js:21
static init(development = false) {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/../users-api/dist/src/routes/users.js:4:24)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
So that I have to change the target to "es5":
"target": "es5"
Which leads to a vicious circle.
I've tried changing the value of "target" and "module" and it always fails something.
Am I missing something here? In theory, typescript 2.2 supports both features so I don't get why I can't transpile.
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"rootDir": ".",
"sourceMap": true,
"module": "commonjs",
"target": "es5"
},
"include": [
"./src/**/*",
"./spec/**/*"
]
}
typescript 2.4.1
node 4.4.7
Try Adding lib section with es2015.promise in tsconfig.json
"lib": [
"dom",
"es5",
"scripthost",
"es2015.promise"
],
You can see the full sample here: https://github.com/basarat/typescript-book/tree/master/code/async-await/es5

Resources