I'm using Intellij Idea to create a NodeJs application in ES6.
My node.exe version is version 6.4.0
I created a simple class :
//wNodeClasses.js
'use strict';
export class wsUrl
{
constructor()
{}
}
I import the module in another file :
require('../../../Root/Libs/Waldata/wsNodeClasses');
When I start the application I always get the error :
d:\Dev\webDev\Root\Libs\Waldata\wsNodeClasses.js:11
export class wsUrl
^^^^^^
SyntaxError: Unexpected token export
at Object.exports.runInThisContext (vm.js:76:16)
I don't use any transpiler , I want to write "pure ES6 code" (I don't want to use Babel or any equivalent)
I understand that NodeJs 6.4.0 can interpret directly ES6 code
Here is my Node.Exe command line :
-max-old-space-size=8192 --expose_debug_as=v8debug
I am a newbie, I suppose I'm missing something obvious, I googled around and I didn't found an answer
I finally found the issue.
NodeJs 6.4.0 with chrome V8 doesn't support Es6 "export" keyword or syntax.
I found a work around using
//Module file
module.exports=
class wsUrl
{
}
and in the consumer :
var wsUrl = require('../../../Root/Libs/Waldata/wsNodeClasses');
...
var MyVar = wsUrl new("test");
I'm still searching to have multiple classes in a same Js file (module) and export them
Thanks for your answer.
I used a different technic (I assume it's just a matter of personal preference) :
//In the module module.exports.myClass1=class myClass1{}
module.exports.myClass2=class myClass2{}
//In the main file (consumer)
var myModule = require('../../../Root/Libs/Waldata/wsNodeClasses');
...
var test=new myModule .wsUrl("param");
This works for me with NodeJs 6.4.0 and intellij (or webstorm)
PS :I'm adding an answer, because I had problems formatting my comment (could not make a "line break"
Related
I am trying to follow this tutorial using nodejs and express: https://pusher.com/docs/beams/reference/web/#npm-yarn
First I did: npm install #pusher/push-notifications-web before adding the code.
But when I add this code in the index.js file:
import * as PusherPushNotifications from "#pusher/push-notifications-web";
const beamsClient = new PusherPushNotifications.Client({
instanceId: "<YOUR_INSTANCE_ID_HERE>",
});
beamsClient.start().then(() => {
// Build something beatiful 🌈
});
I get this error:
SyntaxError: Cannot use import statement outside a module
It's also not very clear to me from the tutorial if the code has to be in the frontend or the backend. I tried both but got the same result.
How can I fix this problem?
The error is caused by the fact that you're trying to use ES module specific features in a regular CommonJS file (the default behavior in Node.js). However, what you're looking at is the Web SDK for Pusher which won't help you achieve your goals.
You need the server SDK for Node.js - https://pusher.com/docs/beams/reference/server-sdk-node/.
Verify that you have the latest version of Node.js installed and you have 2 ways of fixing that
Set "type" field with a value of "module" in package.json. This will ensure that all .js and .mjs files are interpreted as ES modules.
// package.json
{
"type": "module"
}
Use .mjs as file extension instead of .js.
In NodeJS I have:
const fs = require('fs');
if (!fs.existsSync("some_path")) {
...
}
But I get the error:
TypeError: fs.existsSync is not a function
After doing some searching, I read that Webpack brings its own require which clobbers node.js's require, so when you require a node.js core module that webpack can't resolve to one of your files or dependencies, it throws.
(My stack trace includes __webpack_require__)
But how can I fix it?
I was facing the same Error like TypeError: fs.existsSync is not a function
So, I figured out that one extra line was added automatically which was creating this issue in import.
after removing this line from import
import { TRUE } from "node-sass";
the issue has been resolved.
I had the same error that you have. Your vscode might have added a new module to your js file. Remove that module and your app should work just fine.
You can allow webpack to use the Node's require and include fs etc. by targeting node in the config:
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
As described here: https://webpack.js.org/concepts/targets/ and https://webpack.js.org/configuration/target/
I was working on an electron application, I wanted to send a message from node and get in on the react side, but I was having that same issue when requiring ipcRenderer from electron, I tried
import { ipcRenderer } from 'electron';
and
const { ipceRenderer } = require('electron') This leads to an error due to webpack transforming node's require to its own webpack_require. See more info here
What worked for me was to use
const {ipcRenderer} = window.require('electron'); on the react side/renderer side from electron
In my case, I forgot that I'd only imported the promises API, const fs = require("fs").promises, which doesn't have exist or existsSync functions in Node 17.4.0.
To use exist or existsSync, make sure you've imported fs using the sync API (const fs = require("fs")).
Note: I'm adding this answer as a possible solution for future visitors to a canonical thread for the error, not OP who appears to have required fs correctly.
It is nothing to worry about, check your code for something like import { types } from "node-sass";, it would have mistakenly and automatically imported without you know. Remove that line, and everything should work perfectly.
Even if it is not type, it is something from node-sass in your node_modules file, and you can't edit that file.
So look for and remove import { types } from "node-sass"
In my case VSCode added a arbitrary import from electron. After removing it my application worked.
import { Menu } from 'electron';
In my case, i needed to send a message from the node to react. I tried importing ipcRenderer from 'electron'; and const ipceRenderer = require('electron') This results in an error owing to webpack changing the node's require to its own webpack require. See more info here
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
What is the Node.js 'require' equivalent to the following ES6 import?
import RNFetchBlob from 'react-native-fetch-blob'
Thank you
There's no default export in require so you don't have an exact equivalent.
The practice with node modules when you have only one value to export is to make it the module exports:
module.exports = ...
In such a case, you'll be able to import using
var RNFetchBlob = require('react-native-fetch-blob');
Solution
I got it working with:
var RNFetchBlob = require('react-native-fetch-blob').default;
For more details, check out this.
I'm using Visual Studio 2013 (Update 3), Node.js Tools v1.0.20721.02 and Node.js v0.10.31
I'm trying to put each class into its own file.
At design time everything seems fine, intellisense is working and the code compiles without issues.
At runtime however, node tells me it cannot find the classes.
I've reproduced this again and again by creating a new Node console project in Visual Studio
SomeClass.ts
export class SomeClass
{
name: string;
constructor(name: string)
{
this.name = name;
}
}
app.ts
///<reference path="Scripts/typings/node/node.d.ts"/>
import some = require("SomeClass");
var instance = new some.SomeClass("Batman");
console.log(instance.name);
The generated javascript output looks like this:
SomeClass.js
var SomeClass = (function () {
function SomeClass(name) {
this.name = name;
}
return SomeClass;
})();
exports.SomeClass = SomeClass;
//# sourceMappingURL=SomeClass.js.map
app.js
///<reference path="Scripts/typings/node/node.d.ts"/>
var some = require("SomeClass");
var instance = new some.SomeClass("Batman");
console.log(instance.name);
//# sourceMappingURL=app.js.map
Runtime output
module.js:340
throw err;
Error: Cannot find module 'SomeClass'
at Function.Module._resolveFilename (module.js:338:15)
...
Visual Studio Solution structure
This is a standard solution created by the project template in Visual Studio,
shouldn't it just work out of the box?
I've seen quite a few related questions, including this one, which seem to solve the
the issues most people are having, but don't seem to solve my problem.
Try using require("./SomeClass") instead:
node.js resolves require differently when there is no path prepended (see here), so in this case you need to tell it to look in the current directory, not for a core module or inside an (inexistent) node_modules directory.
Further info on why it does not fail before runtime, given by the OP in the comments:
Apparently VS resolves everything whether you prepend './' or not and at runtime node requires './' to be prepended.
Run your program again adding the following line before your require:
console.log("cwd:%s", process.cwd());
And adjust the path you require so it starts at your current working directory (cwd).