How can I fix error with react app creation? [duplicate] - node.js

This question already has answers here:
npx create-react-app not working "Must use import to load ES Module:" [closed]
(4 answers)
Closed 2 years ago.
After run comand npx create-react-app projectName i've recieved this log, and app not created. Why this error happens?
npx: installed 99 in 8.22s
Must use import to load ES Module: C:\Users\Roman\AppData\Roaming\npm-cache_npx\12568\node_modules\create-react-app\node_modules\is-promise\index.js
require() of ES modules is not supported.
require() of C:\Users\Roman\AppData\Roaming\npm-cache_npx\12568\node_modules\create-react-app\node_modules\is-promise\index.js from C:\Users\Roman\AppData\Roaming\npm-cache_npx\12568\node_modules\create-react-app\node_modules\run-async\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 C:\Users\Roman\AppData\Roaming\npm-cache_npx\12568\node_modules\create-react-app\node_modules\is-promise\index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\Roman\AppData\Roaming\npm-cache_npx\1
2568\node_modules\create-react-app\node_modules\is-promise\package.json.

This error is related to the changes that was introduced in: is-promise package version 2.2.0 (that is in node_modules of create-react-app) in which was added support for ES Module style default import, but in version 2.2.2, ESM support was removed because it turns out to be a breaking change.
Try this:
npm install -g --force create-react-app
to update the packages.

Related

Reuse parts of a nextjs app on the console using node command

I created a problem repository here:
https://github.com/tippfelher/so-nextjs-console
Problem description:
Using yarn next dev starts the development server which successfully outputs the model Example on the index-Page.
However, I cannot reuse the same model in a console application.
Running node .\console-app produces the error
import Example from "../models/Example";
^^^^^^
SyntaxError: Cannot use import statement outside a module
Attempts to solve this problem:
Add { "type": "module" } to root package.json and change next.config.js contents to
const config = {
reactStrictMode: true,
}
export default config;
triggers error:
Error: require() of ES Module <PATH>\demo\nextjs-node\app\.next\server\pages\_document.js from <PATH>\demo\nextjs-node\app\node_modules\next\dist\server\require.js not supported.
Edit
node --version
v16.13.1
You do not specify the node version but that error looks like the version of node requires enabling the then experimental es6 module support. In package.json add
"type": "module",
In new NodeJS builds looks like import statements are supported.
Since this is posted around Next, you may get into other compatibility issues, the yarn next dev invokes a cli which does a build and packages compatible modules to be executed by node.
If you are curious, checkout the cli build - https://github.com/vercel/next.js/tree/canary/packages/next/cli

Node.js - Must use import to load ES Module: [duplicate]

This question already has answers here:
Importing in Node.js: error "Must use import to load ES Module" [duplicate]
(7 answers)
Closed 1 year ago.
I googled for a while but I could not find a solution that fixed my issue.
I want to use the fetch function from "node-fetch", but when requiring it in my code, I get the error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/src/index.js from /Users/xvma/stuff/Projekte/React/first-try/test.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 index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/package.json.
Terminal output
In this file I want to use fetch()
My server.js
I hope you guys can help me, I tried deleting my node-components folder & package lock but that did not work.
Also, in my package.lock.json "type"="module" is not set.
It looks like you're using node-fetch 3, which is only distributed as an ESM module, not require()able CJS modules.
For the time being, you can just downgrade to a node-fetch less than version 3.
Alternately, you can go all in on ESM and rename your script to server.mjs and use import everywhere.

Typescript Support for JS Library (node-gtf) in a Express Project

Have a Typescript Express Server for consuming GTFS data using the GTFS library (https://github.com/BlinkTagInc/node-gtfs)
version ("gtfs": "^3.0.4")
Importing the library this way
import { importGtfs } from 'gtfs';
But due to no TS support I m facing this error
require() of ES modules is not supported.
require() of <Project-path>/node_modules/gtfs/index.js from <Project-path>/src/index.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 index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from <Project-path>/node_modules/gtfs/package.json.
Using it this way
import { importGtfs } from 'gtfs';
Found a type Library for GTFS
https://www.npmjs.com/package/gtfs-types
But unable to find a solution to include these types in the Project
This issue is caused by the "type": "module" property in package.json of the gtfs version you're using
type = module would expect es6 syntax however somewhere commonjs require is used.
this is a known issue with node v12.11.0 which was resolved in v12.11.1
you could downgrade the gtfs version to 2.4.4 which doesn't have this type:module property.
If this is a dependency of dependency then add it to resolutions
"resolutions":{
"gtfs": "^2.4.4"
}

NodeJS: loading ES Modules and native addons in the same project

Before the actual questions (see at the end), please let me show the steps that lead to that question through an example:
Creating the project
tests$ mkdir esm && cd esm
tests/esm$ nvm -v
0.37.2
tests/esm$ nvm use v15
Now using node v15.6.0 (npm v7.5.6)
tests/esm$ node -v
v15.6.0
tests/esm$ npm -v
7.5.6
tests/esm$ npm init
package name: (esm) test-esm
entry point: (index.js)
Installing nodehun
tests/esm$ npm install nodehun
added 2 packages, and audited 3 packages in 11s
tests/esm$ npm ls
test-esm#1.0.0 tests/esm
└── nodehun#3.0.2
dependencies of nodehun here
index.js
import { suggest } from './checker.js'
suggest("misspeling");
checker.js
import Nodehun from 'nodehun'
import fs from 'fs';
const affix = fs.readFileSync('dictionaries/en_NZ.aff')
const dictionary = fs.readFileSync('dictionaries/en_NZ.dic')
const nodehun = new Nodehun(affix, dictionary)
export const suggest = (word) => hun_suggest(word);
async function hun_suggest(word) {
let suggestions = await nodehun.suggest(word);
console.log(suggestions);
}
To obtain the required Hunspell dictionary files (affix and dictionary):
tests/esm$ mkdir dictionaries && cd dictionaries
tests/esm/dictionaries$ curl https://www.softmaker.net/down/hunspell/softmaker-hunspell-english-nz-101.sox > en_NZ.sox
tests/esm/dictionaries$ unzip en_NZ.sox en_NZ.aff en_NZ.dic
Running the project
As per nodejs documentation (Determining Module System) to support the import / export:
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
• Files ending in .js when the nearest parent package.json file contains a top-level "type" field with a value of "module".
We add "type": "module" field in the package.json file of the project.
package.json
{
...
"main": "index.js",
"type": "module",
...
}
First Failed Run
tests/esm$ node index.js
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".node" for tests/esm/node_modules/nodehun/build/Release/Nodehun.node
... omitted ...
at async link (node:internal/modules/esm/module_job:64:9) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
Digging a bit on the reason of the above error:
in the documentation on how to load addons, it refers to the use of require
The filename extension of the compiled addon binary is .node (as opposed to .dll or .so). The require() function is written to look for files with the .node file extension and initialize those as dynamically-linked libraries.
once you define your node project as a "type": "module", require it ceases to be supported (as specified in Interoperability with CommonJS):
Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module.
Temporary Solution
After some time searching the documentation, I found a temporary solution: Customizing ESM specifier resolution algorithm:
The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.
The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm.
To enable the automatic extension resolution and importing from directories that include an index file use the node mode.
tests/esm$ node --experimental-specifier-resolution=node index.js
(node:XXXXX) ExperimentalWarning: The Node.js specifier resolution in ESM is experimental.
(Use `node --trace-warnings ...` to show where the warning was created)
[
'misspelling',
'misspending',
'misspeaking',
'misspell',
'dispelling',
'misapplier',
'respelling'
]
There are a some posts that get to this same resolution (ref 1, ref 2).
However, using experimental flags does not seem a proper way to run your application on production.
Failed Alternative with esm package
From that point, several failed attempts have been tried to avoid the use of --experimental-* flags. Doing some search, I found some posts (ref 1, ref 2) recommending the use of the esm package.
esm gets 1.3M downloads per week.
According the read-me file in GitHub, it does not require any changes.
However, at this point, when I try this node -r esm index.js, a new error appears:
tests/esm$ npm install esm
added 1 package, and audited 4 packages in 709ms
tests/esm$ npm ls
test-esm#0.1.0 tests/esm
├── esm#3.2.25
└── nodehun#3.0.2
tests/esm$ node -r esm index.js
tests/esm/index.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: tests/esm/index.js
at new NodeError (node:internal/errors:329:5)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1125:13) {
code: 'ERR_REQUIRE_ESM'
}
The above could be due to a reported issue (Error [ERR_REQUIRE_ESM]: Must use import to load ES Module / require() of ES modules is not supported).
There is proposed patch to fix it, although I do not know how to use it myself.
const module = require('module');
module.Module._extensions['.js'] = function(module, filename) {
const content = fs.readFileSync(filename, 'utf8');
module._compile(content, filename);
};
Questions
Is there a (standard) way to use import / export (ES Modules) without incurring in issues with import addons?
Avoiding the use of the --experimental-specifier-resolution=node flag.
Perhaps esm could be the solution to the above. Is there anything I am doing wrong with the usage esm package?
If it is a correct usage, is there a way to use the proposed patch myself as a working around?
Any hints to help to solve it would be really appreciated.
Note: the final status of the example can be cloned from https://github.com/rellampec/test-esm.git
I ran into a similar problem and fixed it this way:
https://nodejs.org/api/module.html#module_module_createrequire_filename
// The project is "type": "module" in package json
// createRequire is native in node version >= 12
import { createRequire } from 'module';
import path from 'path';
// Absolute path to node modules (or native addons)
const modulesPath = path.resolve(process.cwd(), 'node_modules');
// Create the require method
const localRequire = createRequire(modulesPath);
// require the native add-on
const myNativeAddon = localRequire('my-native-addon');
After some ramblings trying to figure this out got to the root cause.
When using node -r esm index.js, the esm package does already all the work for your (as noted in other answers), and therefore (not mentioned in other answers):
the package.json should be updated by removing "type:" "module" (as it creates unintended interactions between the native node ES Modules feature and the esm package you installed)
Aside note: if you tried to use node ES Modules and then you try to switch to esm package, it is very easy to miss this point.

How to use named imports (ES 6) in NodeJS 14.x?

I have code which I like to use inside nodejs (14.4) and the browser. For this code to work inside nodejs I need named imports like
import {Vector3} from "three;
ES 6 modules in general are working fine with the following changes:
package.json:
"type": "module",
An launching nodejs with --experimental-specifier-resolution=node so I don't have to specify file extensions. But for named imports nodejs still prints out:
SyntaxError: The requested module 'three' is expected to be of type CommonJS, which does not support named exports.
There is a Stackoverflow post suggesting the usage of esm package loader. Unfortunately it has a bug making TypeScript "reflect-metadata" unusable (Issue: https://github.com/standard-things/esm/issues/809) So I can't use that.
TL;DR; How can I enable named ES 6 modules in nodeJs 14.4 without ESM package loader? type: module and launch arg are already set.
This may not be the perfect answer but I solved my problem by switching the code base to Type Script (TS):
For browser, I can configure ts to use es 6 modules
For node, I can configure ts to use node modules
--> Everybody is happy

Resources