ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package - babeljs

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.

Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Related

How to add babel and polyfills to a RequireJs project?

I am working on a legacy project which uses RequireJs to load and resolve all the dependencies. It works fine on modern browsers, but i need to add support for IE11.
I tried to use babel 7 with #babel/preset-env with following .babelrc
{
"presets": [
["#babel/preset-env", {
"useBuiltIns": "usage",
"corejs": 3,
"targets": {
"browsers" : ["ie>=11"]
},
"modules": false
}]
],
"compact": false
}
the import statements injected by the preset as following
import "core-js/modules/es.function.name.js";
cause error "import statements can't be used outside a module". Even when I use modules: "amd", then core-js is imported as
define(["core-js/modules/es.array.filter.js", "core-js/modules/es.object.to-string.js", "core-js/modules/es.string.includes.js", "core-js/modules/es.function.name.js", "core-js/modules/es.regexp.exec.js", "core-js/modules/es.string.split.js", "core-js/modules/es.string.small.js", "core-js/modules/es.string.search.js"], function (_esArrayFilter, _esObjectToString, _esStringIncludes, _esFunctionName, _esRegexpExec, _esStringSplit, _esStringSmall, _esStringSearch) {
"use strict";
//...
});
which throws error like "define is not defined in require.js".
When using useBuiltIns: "entry", and then including core-js as
require(["core-js", ../other modules], function(corejs, ...){
}
)
in the main.js file, it fails to correctly resolve the path of the files even though I have included the path to core-js in require.config.paths.
I tried #babel/runtime and #babel/plugin-transform-runtime but no luck there.
So my question is what would be the best way to add babel and the required polyfills in my RequireJs project so that it is compatible with IE 11?

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

"Unexpected token stripe" when trying to deploy Firebase Functions

I'm trying to incorporate Stripe into an iOS app using Firebase Functions. I'm following the Stripe documentation for "Accepting a payment" in Swift with Node backend. I first did npm install --save stripe. That finished with no errors. Then I did npm install. My index.js looks like this so far:
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const functions = require('firebase-functions');
const stripe = require('stripe')('sk_test_...');
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
});
const clientSecret = paymentIntent.client_secret
When running firebase deploy I get: 11:29 error Parsing error: Unexpected token stripe. Line 11 char 29 in my file is the stripe.paymentIntents...
This is my first time using Firebase Functions or Stripe, so I'm at a loss here. I appreciate any help.
EDIT:
Here's the contents of my package.json file.
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"stripe": "^8.55.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
This error is because on the cloud environment the stripe library is not installed before you require it.
npm install does install the dependencies but in your local environment, to install them on the Cloud Functions envirornment you need to edit the package.json file from the Cloud Function.
This to add the dependencies that it will be required by the function.
This is done by adding the dependency section to the package.json file
It will lok something like:
{
"name": "sample-name",
"version": "0.0.1",
"dependencies": {
"escape-html": "^1.0.3",
"stripe": "^8.24.0"
}
}
EDIT
With this code it works on Cloud functions:
const stripe = require('stripe')('<My Secret Key>');
exports.helloWorld = (req, res) => {
let paymentIntent = null;
paymentIntent = stripe.paymentIntents.create({
amount: 2000,
currency: 'usd',
description: 'My first payment',
});
let message = req.query.message || req.body.message || 'Hello World!';
res.status(200).send(message);
};
Apparently the issue was the await because HTTP Cloud Functions work on a Synchronous way
I see this question is old but I ran into this exact issue and couldn't find an answer.
I had my backend functions folder nested within my overall app and I had let firebase generate some files for me, including a lint configuration. So, I ended up with two lint config files in my project total. The firebase generated one tried to enforce double quotes and the one I created tried to enforce single quotes. I ended up just deleting the generated lint config and it works fine now.

Trying to write a vuepress plugin

(The doc on writing a plugin is pretty sparse...)
THE GOAL
Create a plugin to add headers to a page.
THE ATTEMPT
Created a plugin following guidelines and an example plugin (that presumably works...) to do something similar.
THE ISSUE
Plugin won't load.
config.js
plugins: [
[
'vuepress-plugin-headertags',
{ headerTags: ["<script src='https://cdn.jsdelivr.net/npm/netlify-identity-widget#1.5.2/build/netlify-identity-widget.min.js'></script>"]}
]
],
(the <script> tag is what I'm trying to insert, in this instance.
PLUGIN index.js
const { path } = require('path')
// was: const { path } = require('#vuepress/shared-utils')
// dunno. No documentation on this...
// got the current version from the 'default-theme' code
module.exports = (options) => ({
define () {
return {
headerTags: options.headerTags || []
}
},
enhanceAppFiles () {
return [path.resolve(__dirname, 'enhanceAppFile.js')]
},
globalUIComponents: ['HeaderTags']
})
PLUGIN INSTALLATION
I published it to npm as vuepress-plugin-headertags, and then installed it with:
yarn add -D vuepress-plugin-headertags
Here's the relevant package.json content:
{
"name": "vuepress-netlifycms",
"version": "0.0.0",
"scripts": {
"dev": "vuepress dev",
"build": "vuepress build",
"debug": "node --nolazy --inspect=9229 /home/rickb/.yarn/bin/vuepress build"
},
"devDependencies": {
"vuepress": "^0.14.8",
"vuepress-plugin-headertags": "^1.0.3"
},
"dependencies": {}
}
VUEPRESS INSTALLATION
I cloned the vuepress repo from git and did a yarn link, which makes it globally available. With that, I can trace it in the debugger via the 'debug' script.
TRACING
I've followed the VP source code in the debugger and get to resolvePathPackage() in moduleResolver.js. The incoming path is not correct:
/home/(...)/VuePress-NetlifyCMS/vuepress-plugin-headertags
It should be:
/home/(...)/VuePress-NetlifyCMS/node_modules/vuepress-plugin-headertags
At any rate, it doesn't resolve, even after the 'normalization' process.
MORE EYES
I need more eyes on this to help me figure it out. The project is already up on github as 'rickbsgu/VuePress-NetlifyCMS.git'. If you do an install, the plugin will be in the project directory under 'node_modules/vuepress-plugin-headertags'
Any thoughts appreciated
And it works, now. Two problems:
Version I was running/debugging was not the same as the version in package.json. There is the vuepress executable and the vuepress libraries the plugin requires. The library was always the older version at runtime.
I needed to change the path import in index.html from const { path } = require('path') to const { path } = require('#vuepress/shared-utils'). That's my doc issue - I don't see that documented anywhere.
Thanks #Sun Haoran for getting me to look in the right place.

regeneratorRuntime is not defined (how keep babel from including that polyfill?)

I continue to get:
App.jsx:11 Uncaught ReferenceError: regeneratorRuntime is not defined
on any line that does an async. I don't what that polyfill, but I am having a hard time getting rid of it:
app.jsx:11)
const fetcher = (async () => {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"#babel/preset-react": "^7.0.0",
"#types/react": "^16.8.17",
"babel-preset-env": "^1.7.0"
here is the .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"chrome": ">70",
},
"exclude": ["transform-regenerator"]
},
"#babel/preset-react"
]
]
}
If you want to use async, await with (ES6 or ES Next) then you must need to install #babel/polyfill but you don't need to write anything in babelrc file. Just install
npm install --save #babel/polyfill
From the documentation:
Because this is a polyfill (which will run before your source code),
we need it to be a dependency, not a devDependency
And finally you need to import #bable/polyfill in your mainJS (App.js) file like:
import "#babel/polyfill";
This appears to be a bug in the parcel js bundler.
https://github.com/babel/babel/issues/9971