babel-register doesn't work for subsequent require statements - node.js

I'm building an isomorphic (universal) React.js app with Express.js. My server and client code share a Routes.jsx file employing ES2017 syntax and, well, JSX.
I understand babel-register should transpile this ; however, the following code generates an error when executed:
require('babel-register')({
presets: [
'es2017',
'react',
]
})
const routes = require('./Routes.jsx')
The first line of Routes.jsx is:
import React from 'react'
The error is:
(function (exports, require, module, __filename, __dirname) { import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
I am absolutely baffled at why this isn’t working. The correct babel modules are installed. Thanks for pointers!

The es2017 preset only includes newly added features for ES2017, so it will not include converting module syntax.
Using babel-preset-env is likely your easiest option.

Related

my code does not run with the index.js file only with index.mjs > Node.js

good guys I'm still learning and since I'm facing this type of error, I don't know what to do for the code to accept calling as index.js, should I be worried about that? all files i have to change the file to "index.mjs" to work correctly. what I would like to know is if I should accept this or do I have to fix it to run as index.js could you tell me if there is a problem with everything being in mjs?
const inquirer = require('inquirer')
const chalk = require('chalk')
inquirer.prompt([
{name: "p1", message: `${chalk.green("what is your first name: ")}`},
{name: "p2", message: `${chalk.green("what is years old: ")}`}
])
.then((answers) => {
console.log(`${chalk.yellow(answers.p1, answers.p2)}`)
const infoName = answers.p1
const infoAge = answers.p2
console.log(`his name is ${chalk.red(infoName)} and your age is ${chalk.red(infoAge)} years old`)
}).catch((err) => {
console.log(err)
})
this is the error that appears when I try to run with the index.js file
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\node_modules\inquirer\lib\inquirer.js from C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js not supported.
Instead change the require of inquirer.js in C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js:1:18) {
code: 'ERR_REQUIRE_ESM'
}
Node.js v18.13.0
baixei a versão mais recente,
The reason for this is that inquirer is a pure-ESM package.
What is ESM?
Node.js appeared long before import/export support in JS. So it's used (and still is) so called require.js for imports.
Later, Node.js added support for ES modules, but with some limitations. One of these limitations is that ESM script can only be imported from another ESM script.
What to do?
The Node.js ecosystem is slowly migrating to the ESM. So you can continue using ESM, but you should avoid using require and use import instead. E.g.:
import inquirer from 'inquirer';
If you want to use require, you have to downgrade inquirer to version 8+
You can also use TypeScript with esModuleInterop and always use import/export.

NodeJS (Server): ReferenceError: require is not defined when type: module

On Node 13.8 I'm trying to use import / export.
EG:
import {ChatClient, Message, MessageParser} from './chat-client/module.js';
But when i do this, I get
SyntaxError: Cannot use import statement outside a module
So in my package.json I set "type" : "module" but now when I try to use const io = require('socket.io-client');
I get ReferenceError: require is not defined
Is there a way to use import / export AND require?
The original error, does that just mean I have to wrap my library in a NPM library? It's a Library that's used both front end and backend so using import / export is important.
Thanks
As the documentation says:
No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.
https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname
You can't use both natively. If you want to do that use Babel to transpile your code.
ES Modules in Node >= 14 do not support require.
However if you want to add it, u have to add this at the top of your file:
Everything should work fine.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Several points:
Use .mjs instead of .js.
Never use require.
It is optional to use "type": "module".
If you use {"type":"module"} you won't be able to use require function in your project. So if you want to use require as well import you need to add the following properties in package.json.
"babel": {
"presets": [
"stage-3",
"latest"
]
}
"babel-preset-latest": "^6.16.0"
"babel-preset-stage-3": "^6.5.0"

What am I missing in my Express app when trying to render React SSR?

I'm going nuts over this issue. I can't figure out what I'm missing.
My setup is the following:
Express server created with Express Generator
React app created with CRA
I would like to be able to do SSR for my React scripts.
Folder structure is like this:
src/
bin/
www
routes/
index.js
app.js
.babelrc
client/ (React app files)
src/
App.js
I start the Express server using the following script in my package.json:
nodemon --exec babel-node ./src/bin/www
I try to render a React component in routes/index.js by doing the following:
import React from 'react'
import { renderToString } from 'react-dom/server'
import App from '../client/src/App';
...
.babelrc looks like this:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
And in the file /bin/www I've put the following (at the top):
require("#babel/register")({
presets: ["#babel/preset-react"]
})
...
But all I can get out is.....
SyntaxError: Unexpected token import
which points to:
/srv/app/customer-server/src/client/src/App.js:1
(function (exports, require, module, __filename, __dirname) { import React, { Component } from 'react';
What am I missing here? Am I doing the impossible for this kind of setup?
Thank you
The answer is that I was using Docker with mounted volumes which was causing the error, it was all working fine after I got that figured out.

how to use node module with es6 import syntax in typescript

I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5

New to React / Babelify; How to fix "Accessing PropTypes" warning

I'm new to both React and Babelify.
I'm using Node to compile a web app. Right now I'm doing this:
browserify({debug: true})
.transform(
babelify.configure({
comments : false,
presets : [
"react",
"babili",
],
})
)
.require('./app.js', {entry: true})
.plugin(collapse)
.bundle()
.on("error", function (err) {
console.log("Error:", err.message);
})
.pipe(fs.createWriteStream(destination));
My app is a VERY trivial "Hello, World!" proof-of-concept at the moment that's about this complex:
class Renderer {
render () {
ReactDOM.render(
<div>Hello, World!</div>
document.querySelector("#react-app")
);
}
}
module.exports = Renderer;
I'm getting this warning:
Warning: Accessing PropTypes via the main React package is deprecated, and
will be removed in React v16.0. Use the latest available v15.* prop-types
package from npm instead. For info on usage, compatibility, migration and more,
see https:/gfb.me/prop-types-docs
Warning: Accessing createClass via the main React package is deprecated,
and will be removed in React v16.0. Use a plain JavaScript class instead. If
you're not yet ready to migrate, create-react-class v15.* is available on npm
as a temporary, drop-in replacement. For more info see
https:/gfb.me/react-create-class
Error: [BABEL] /home/gweb/code/app.js: Unknown option:
/home/gweb/code/node_modules/react/react.js.Children. Check out
http:/gbabeljs.io/docs/usage/options/ for more information about options.
A common cause of this error is the presence of a configuration options
object without the corresponding preset name. Example:
Invalid:
`{ presets: [{option: value}] }`
Valid:
`{ presets: [['presetName', {option: value}]] }`
For more detailed information on preset configuration, please see
http:/gbabeljs.io/docs/plugins/#pluginpresets-options. (While processing
preset: "/home/gweb/code/node_modules/react/react.js") while parsing file:
/home/gweb/code/app.js
I read the recommended stuff, but I'm new enough to both that I can't quite get a handle on it. I also read a bunch of other articles and SO posts, but none of them (that I could find) had this set (browserify, babelify, react).
My goal at the moment is just to get it transpiling with support for the React syntax (which is JSX, from what I understand?), so I can start playing with it and learning both libraries. What's the fastest way to get this implemented (I don't necessarily need most efficient or best; I'd rather have the easiest-to-understand incantation at this stage, so I can have things transparent while I learn).
It is not your setup issue but problem is with your import statements, i'm assuming you are importing react and PropTypes from react
import React, { PropTypes } from 'react';
So, using PropTypes from react library has been deprecated as mentioned in warning and you need to install PropTypes as a standalone library from npm and use that instead.
npm install prop-types --save and then do,
import PropTypes from 'prop-types', for more info https://www.npmjs.com/package/prop-types
this will resolve your first warning, also for second warning you need to install and use https://www.npmjs.com/package/create-react-class.
for the babel error please check if you have both required libraries installed.
https://www.npmjs.com/package/babel-preset-react,
https://www.npmjs.com/package/babel-preset-babili
Do you have an import of the form import * as React from 'react'?
If so, try replacing it with import React from 'react'.
The * imports everything from react, including the deprecated exports, and that's what triggers the warnings.

Resources