Import not working on Node.js version 11.8.0 - javascript

I am writing a simple program that uses a object full of dictionary words. I want to import that object from a different file as it is very large. When trying to import it I get an error that looks like Node.js doesn't know what it is.
I have already tried reinstalling the latest version of Node.js.
Here is the important code:
import {dict} from './words_dictionary'
And here is all of it:
import {dict} from './words_dictionary'
function exists(obj,str) {
if(obj[str]) {
return true
} else {
return false
}
}
console.log(exists(dict, 'hello'))
Here is the gist of the dictionary code:
export let dict = {a: 1, aa: 1, aaa: 1, aah: 1, aahed: 1, aahing: 1, aahs:
1, aal: 1, aalii: 1, aaliis: 1, aals: 1, aam: 1, aani: 1, aardvark: 1,
aardvarks: 1,...~3000 more}
I expected true, but I got this error:
SyntaxError: Unexpected token {
at new Script (vm.js:84:7)
at createScript (vm.js:264:10)
at Object.runInThisContext (vm.js:312:10)
at Module._compile (internal/modules/cjs/loader.js:696:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
at Function.Module._load (internal/modules/cjs/loader.js:560:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
ECMAScript 6 is now working, but I am now getting the error of dict not being defined. Could this have something to do with the file size, because I have checked multiple times for spelling errors?

Have you been able to use the import keyboard elsewhere in your code? The issue here may be that you aren't transpiling your code into ECMAScript 5. Since import is an ECMAScript 6 feature, it hasn't yet been fully supported by Node.js. If you use a tool like Babel to transpile your code, you may fix this issue. If you don't want to do this, try using require instead.
As noted, in Node.js 9+ you can also use it in .mjs files with the --experimental-modules flag enabled.
node --experimental-modules file.mjs
Node.js import compatibility

It's only supported with an experimental flag. You should use the --experimental-modules flag.
Or just use require simple as that or if you really want, you can transpile your code with browserify, babel or parcel or whatever.
I think this should work if you run code like this:
node --experimental-modules index.mjs
Note that it uses the mjs extension (modular JavaScript I think).

You try this. Hope it helps
const 'your_variable' = require('your_required_module or file_path')
In your case
const dict = require( './words_dictionary')

Install necessary packages
npm install #babel/core #babel/register #babel/preset-env --save-dev
Add start.js file
// Transpile all code following this line with babel and use
'#babel/preset-env' (aka ES6) preset.
require("#babel/register")({
presets: ["#babel/preset-env"]
});
// Import the rest of our application.
module.exports = require('./server.js')

Related

How to use node_modules in Deno as typescript imports?

Project: REST API for serving information stored in a neo4j graph database.
Backend: Deno
I am farely new to deno, but I'm not new to typescript, having used it in Angular frequently.
Problem: I want to use a driver to connect my neo4j database to my backend, but there is no neo4j driver made for Deno. I have scoured the internet and documentation for solutions, and have been trying to import the javascript library using the node modules import tool that has been suggested from similar answers and is supported by the deno team.
Essentially, I do npm install neo4j-driver, and then add the following code to my deno project.
Failed Solution: the javascript node modules wrapper
I implement call this function as a test for my deno server in a server.ts file.
The command I use for deno is: deno run --allow-all --unstable server.ts
neo4j_conn.ts file: (called by server.ts)
import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
export async function testconnection(uri: string, user: string, password: string) {
//This is the line that fails.
var neo4j = require('neo4j-driver').v1; //this fails whether or not I include the .v1 or not.
var driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
await driver.close()
}
This returns the following error:
error: Uncaught (in promise) Error: Cannot find module 'net'
Require stack:
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/handshake.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/neo4jconn.ts
at Function._resolveFilename (https://deno.land/std#0.97.0/node/module.ts:273:19)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:380:29)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
at require (https://deno.land/std#0.97.0/node/module.ts:1158:16)
at Object.<anonymous> (file:///mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js:24:29)
at Module._compile (https://deno.land/std#0.97.0/node/module.ts:168:36)
at Object.Module._extensions..js (https://deno.land/std#0.97.0/node/module.ts:1109:10)
at Module.load (https://deno.land/std#0.97.0/node/module.ts:147:34)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:413:14)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
As far as I could tell, I had done everything right, but I am a little in over my head when it comes to the typescript/js module translation.
My file structure is as follows:
package.json
package-lock.json
server.ts
neo4j_conn.ts
node_modules -|
|
:
Neo4j developer js docs: https://neo4j.com/developer/javascript/
Deno node modules "require": https://doc.deno.land/https/deno.land/std#0.97.0/node/module.ts
If you look at the Node compatibility layer README in std you will realize that right now there is no compatibility module for the net library. The compatibility will improve day by day, but take into account that Deno is not a drop in replacement for Node, but a whole new thing that won't work with Node libraries by default
https://deno.land/std#0.97.0/node

Javascript modules - Cannot use import statement outside a module

I am new to Javascript and I am trying to learn modules from a tutorial. In have a folder in visual studio code/VScode which has two files, script.js & external.js.
Script.js imports content from external.js and prints text to console. I get the below error when I run script.js from vs code, with node.js run configuration. Can someone please tell me why this happens and how to fix it ? In comparison, imports in Java are simple.
import {keyValue} from './external.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1070:16)
at Module._compile (internal/modules/cjs/loader.js:1120:27)
external.js :
export let keyValue = 1000;
script.js :
import {keyValue} from './external.js';
console.log(keyValue);
UPDATES :
Node version - v12.16.2, upgraded to v14.4.0.
What's the version of node.js?
If node.js is version 13 or above, you can do either:
add { type: "module" } to package.json.
{
...
scripts: "...",
type: "module"
}
rename .js to .mjs
If it's under 13, rename .js to .mjs, and run with additional params --experimental-modules.
node --experimental-modules script.js
Or
You can also fix the import statement outside a module issue
by not using the import statement and using the dynamic import function instead.
script.js
import("./external.js").then((module) => {
console.log(module.keyValue);
});
This form also supports the await keyword.
let module = await import('./external.js');
console.log(module.keyValue)
it's because you are using es6 modules instead of the default module system for node which is common js. you could either use babel to transpile it or to use the .mjs extension

How do I add more than one Gatsby Plug-in using the gatsby-config.js file?

I am trying to add additional Gatsby Plug-ins to a Gatsby Project. I want to add 'gatsby-plugin-styled-components' to the gatsby-config.js file. Any help would be appreciated. Newbie to React and learning a lot fast.
added already and threw errors all over the place after running npm run build
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.org/docs/gatsby-config/
*/
module.exports = {
plugins: [`gatsby-plugin-emotion`],
}
gatsby-starter-hello-world#0.1.0 build /Users/jappleman/code/hello-world/tutorial-part-two
gatsby build
error We encountered an error while trying to load your site's gatsby-config.
Please fix the error and try again.
Error: /Users/jappleman/code/hello-world/tutorial-part-two/gatsby-config.js:8
plugins: ['`gatsby-plugin-emotion`],['`gatsby-plugin-styled-components'],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unterminated template literal
- v8-compile-cache.js:226 NativeCompileCache._moduleCompile
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:226:18
- v8-compile-cache.js:172 Module._compile
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:172:36
- loader.js:712 Object.Module._extensions..js
internal/modules/cjs/loader.js:712:10
- loader.js:600 Module.load
internal/modules/cjs/loader.js:600:32
- loader.js:539 tryModuleLoad
internal/modules/cjs/loader.js:539:12
- loader.js:531 Function.Module._load
internal/modules/cjs/loader.js:531:3
- loader.js:637 Module.require
internal/modules/cjs/loader.js:637:17
- v8-compile-cache.js:159 require
[tutorial-part-two]/[v8-compile-cache]/v8-compile-cache.js:159:20
- get-config-file.js:33
[tutorial-part-two]/[gatsby]/dist/bootstrap/get-config-file.js:33:22
- Generator.next
- new Promise
gatsby-config.js exports an object
module.exports = {}
and within that object, the plugins you want to use on your project are specified as an array of plugin names (strings) that you have already installed as dependencies to your project (for example by typing npm install gatsby-plugin-react-helmet or yarn add gatsby-plugin-react-helmet into your terminal).
module.exports = {
plugins: [
`gatsby-plugin-react-helmet`
]
}
However, some of the plugins you will install might need some options to be set in order to work correctly. So these plugins should each be specified as an object within the same plugins array. And in this case, the value of each object's resolve property is the name of the plugin, usually followed by an object for their own options.
module.exports = {
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-remark`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src/data/`
}
}
]
}
For more information see Using a Plugin in Your Site
Also, given that your error is caused by a SyntaxError, please see MDN - Template_literals for information on backticks vs regular quotes, the differences between:
`gatsby-plugin-styled-components` & 'gatsby-plugin-styled-components'
& why the following line might be causing the Unterminated string literal SyntaxError:
plugins: ['`gatsby-plugin-emotion`],['`gatsby-plugin-styled-components']
After that, if the solution is not obvious, try changing your plugins to either of the following:
plugins: [`gatsby-plugin-emotion`],[`gatsby-plugin-styled-components`]
or
plugins: ['gatsby-plugin-emotion'],['gatsby-plugin-styled-components']

How to setup node environment to run ES6 codes involving syntax like `import ... from ...`?

I want to run the following codes based on source code here containing some ES6 syntax like import ... from ...:
import rgb from "./rgb";
import array from "./array";
import date from "./date";
import number from "./number";
import object from "./object";
import string from "./string";
import constant from "./constant";
var interpolateValue = function(a, b) {
// set var t and c
var t = typeof b, c;
// if b is null or t is type boolean,
return b == null || t === "boolean" ? constant(b)
: (t === "number" ? number
: t === "string" ? ((c = color(b)) ? (b = c, rgb) : string)
: b instanceof color ? rgb
: b instanceof Date ? date
: Array.isArray(b) ? array
: isNaN(b) ? object
// (a,b) is 2 function args
: number)(a, b);
}
console.log(interpolateValue("foo", "bar")(0.5));
I tried to run this code inside a node project with d3.js as dependencies. However, I recieved the following error pointing at import in console:
SyntaxError: Unexpected reserved word
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 Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
my question:
How can I set up a node environment step by step in order to run codes with ES6 syntax?
with help of the first answer, I managed to set up the environment to run successfully (details can be found in the second solution), but the speed of compiling seems slow. Does anyone know why?
Thank you!
Yes you need babel. Have you checked out the documentation here:
https://babeljs.io/docs/setup/#installation
$ npm install --save-dev babel-core
then:
require("babel-core").transform("code", options);
after that make sure you've setup your .babelrc file:
{
"presets": ["es2015"]
}
Hope that helps!
as #abigwonderful pointed out the babel site provided ways to setup environment to translate ES6 code to ES5. Below is the solution which I found comfortable to me at this moment.
create a directory and run npm init at its terminal;
move inside this directory's terminal run npm install --save-dev PackageName for the following packages: browserify, babel-cli, babelify, babel-preset-es2015;
run npm install --save d3;
run echo '{ "presets": ["es2015"] }' > .babelrc;
by now, env is all set. when your scritp.js is ready, in the terminal run ./node_modules/.bin/babel-node script.js
It seems quite slow, as brackets warned that there are over 30,000 files in the project, some of its features will be disabled. maybe for the similar reasons, this method above works but seems slow to me. Does anybody know why and how to solve it?
Thanks!

Gulp Node.js Istanbul Isparta

I'm trying to get unit tests coverage with Istanbul and Isparta, and I'm having some trouble.
Actually, here's my gulp file tasks:
gulp.task('pre-test', ['default'], function() {
return gulp.src('src/app/**/*.js')
.pipe(plumber())
.pipe(istanbul({
instrumenter: isparta.Instrumenter,
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function() {
return gulp.src('src/test/**/*.js')
.pipe(mocha({reporter: 'spec'}))
.pipe(istanbul.writeReports({}));
});
When I start the gulp "test" task, I have the following errors:
[08:34:17] Plumber found unhandled error:
Error in plugin 'gulp-istanbul'
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Line 1: Unexpected token
[08:34:17] Finished 'pre-test' after 2.11 s
[08:34:17] Starting 'test'...
stream.js:94
throw er; // Unhandled stream error in pipe.
^
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Object.Module._extensions.(anonymous function) [as .js] (C:\projects\nodejs\mon-notaire\node_modules\gulp-istanbul\node_modules\istanbul\lib\hook.js:109:37)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at C:\projects\nodejs\mon-notaire\node_modules\mocha\lib\mocha.js:192:27
at Array.forEach (native)
npm ERR! Test failed. See above for more details.
How can I prevent these errors from occurring?
Have you set up .babelrc?
If you're using the latest version of isparta, which depends on babel v6, then you need to set up .babelrc like the following. ( You also need to do npm install --save-dev babel-preset-es2015 )
{
"presets": [
"es2015"
]
}
From gulp-istanbul github page.
var isparta = require('isparta');
var istanbul = require('gulp-istanbul');
gulp.src('lib/**.js')
.pipe(istanbul({
// supports es6
instrumenter: isparta.Instrumenter
}));
This line :
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Means that there is a problem in your code in ConsoleLogger.js , so you might want to check that file out.
This Line :
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
Suggests that you are using ES6, but your gulp task is not transpiling it to ES5 before running it, which is why you are getting the error.
I have made a yeoman generator which creates a project for exactly this purpose (writing nodeJs projects in ES6) and includes code coverage using istanbul with source code mapping. You might want to take a look at that.
Otherwise, here is my working gulpfile from that generator.
I use istanbul, along with a module called remap-istanbul.
The error message indicates that you are using ES6, but the gulp-istanbul doesn't support it by default.
Of course, you can write your functions to compile the ES6 codes, but considering you are using gulp in this case, IMHO the simplest way you can do is to use gulp-babel-istanbul instead of gulp-istanbul, no need to change your code attached above at all.
import istanbul from 'gulp-babel-istanbul'
And the rest of the code remains the same.

Categories

Resources