How to correctly use import in Node JS - javascript

I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.
What do I need to change to get import to work?
I have 3 simple files in the same directory.
package.json
main.js
Utility.js
package.json
{
"name": "node_template",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Utility.js
'use strict';
class Utility {
constructor() {
}
}
export { Utility };
main.js
"use strict";
(async ()=>{
import { Utility } from './Utility.js';
var utility = new Utility();
console.log( "Main" );
})();
When I run "node main.js" I get the following error:
node -v
v16.0.0
node main.js
main.js:4
import { Utility } from './Utility.js';
^
SyntaxError: Unexpected token '{'
←[90m at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m at async link (node:internal/modules/esm/module_job:64:21)←[39m

main.js
(async () => {
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();
Note:
The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.
Links:
https://v8.dev/features/dynamic-import
https://flaviocopes.com/javascript-dynamic-imports/

Related

Why npm start not working after npm init?

I have initiated a new project with NPM :
npm init
I have installed the socket.io-client package.
package.json:
{ "name": "client", "version": "1.0.0", "description": "", "main": "script.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "socket.io-client": "^4.5.4" } }
script.js:
import { io } from "socket.io-client";
const socket = io('http://localhost:3000')
socket.on('connect', () => {
console.log('Hello - ' + socket.id)
})
The error I get:
npm ERR! Missing script: "start"
I have added the start command to package.json:
"start": "node script.js"
Now I get:
SyntaxError: Cannot use import statement outside a module
I have tried adding start command, and did not worked.
You can try one of these:
Add type="module" to whereever you import your script.
Add "type": "module" to your package.json file.
See more here: "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

How to set up the preact-render-to-string on the express

Please tell me how to set up the preact-render-to-string on the express.
https://github.com/preactjs/preact-render-to-string#render-jsx--preact--whatever-via-express
https://expressjs.com/en/starter/installing.html
I built it reading the above links. The source code is on there, but I'm not used to node
I don't know how to execute it(Or I don't know if I'm failing to build the environment.).
I believe my installation procedure can be found in package.json(dependencies and devDependencies). So, below is my package.json.
My package.json:
{
"name": "y",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"preact": "^10.5.14",
"preact-render-to-string": "^5.1.19"
}
}
My app.js (Same as Document):
I didn't know what to do with the file name, so I used app.js.
import express from 'express';
import { h } from 'preact';
import render from 'preact-render-to-string';
/** #jsx h */
// silly example component:
const Fox = ({ name }) => (
<div class="fox">
<h5>{ name }</h5>
<p>This page is all about {name}.</p>
</div>
);
// basic HTTP server via express:
const app = express();
app.listen(8080);
// on each request, render and return a component:
app.get('/:fox', (req, res) => {
let html = render(<Fox name={req.params.fox} />);
// send it back wrapped up as an HTML5 document:
res.send(`<!DOCTYPE html><html><body>${html}</body></html>`);
});
Run and Error:
$ node app.js
src/pr/ex/app.js:1
import express from 'express';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
I think I am running it wrong or failed to build the environment, what can I do to make it run successfully?
node is installed with nodebrew. The current status is as follows.
$ nodebrew list
v16.6.2
current: v16.6.2
Edit:
I tried the answer.
add the top-level "type" field with a value of "module"
The error SyntaxError: Cannot use import statement outside a module is gone and different error occurred.
$ node app.js
file:///src/pr/ex/app.js:8
<div class="fox">
^
SyntaxError: Unexpected token '<'
at Loader.moduleStrategy (node:internal/modules/esm/translators:146:18)
at async link (node:internal/modules/esm/module_job:67:21)
Since I am using preact (I must be using htm internally), it is odd that Unexpected token '<' would be an error.
package.json after editing:
{
"name": "y",
"version": "1.0.0",
"type": "module",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"preact": "^10.5.14",
"preact-render-to-string": "^5.1.19"
}
}
Possible solutions:
Use require:
const express = require('express')
const { h } = require('preact')
Save your app.js file as a .mjs file (Node13+ only)
Add { type: 'module' } in your package.json

A problem with import in TypeScript/Electron.js

I have a file index.ts:
import { app, BrowserWindow } from 'electron'
let win
app.on('ready', () => {
win = new BrowserWindow({
minHeight: 640,
minWidth: 480,
frame:false
})
win.loadFile('index.html')
})
If I try to run with: npm start, I got an error:
import { app, BrowserWindow } from 'electron'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1051:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
at Module.load (internal/modules/cjs/loader.js:981:32)
at Module._load (internal/modules/cjs/loader.js:881:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at loadApplicationPackage (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:109:16)
at Object.<anonymous> (D:\VS Projects\Electron App\node_modules\electron\dist\resources\default_app.asar\main.js:155:9)
at Module._compile (internal/modules/cjs/loader.js:1145:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
My package.json:
{
"name": "electron-app",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"dependencies": {
"electron": "^10.1.2"
},
"devDependencies": {},
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
How I can solve it?
It looks like you are trying to use TypeScript with Electron. Electron has types available, however it doesn't directly support executing TypeScript right out of the box. You will need to perform some additional steps to get things working. This goes a bit out of scope of an answer, and would need to be more of a tutorial or example, so I'll provide you with an example from GitHub.
You can view an example of getting started with TypeScript and Electron Here.
Electron runs through node.js and node.js is behind and uses commonjs import syntax.
To import we do:
const {app} = require("electron");
// equivalent to
//import {app} from 'electron' <- don't use in electron
to export we do:
module.exports = app;
// equivalent to
//export default app; <- don't use in electron

Yarn/Node - JavaScript - Issues with Import and Export

I want simply import a function from an another file and I'm getting this error message:
SyntaxError: Cannot use import statement outside a module
I'm not using any html file. I'm using only js files with webpack that returns the result on the console with yarn start
Here is the code of the file that contains the function I want to export:
export function assert(value, desc) {
return value ? console.log(desc) : console.log('fail')
}
Here is the code of the file that I want to import the function:
import {assert} from './assert.js'
function juggle() {
var result = 0;
for(var n=0; n < arguments.length; n++) {
result += arguments[n]
}
this.result = result
}
var ninja1 = {}
var ninja2 = {}
juggle.apply(ninja1, [1,2,3,4])
juggle.call(ninja2, 5,6,7,8)
assert(ninja1.result === 10, "juggled via apply")
assert(ninja2.result === 26, "juggled via call")
Here is my package.json:
I don't know if it is userful to solve this issue, but here is, if you want to see it.
{
"name": "c",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "node Cap_03/01_apply_e_call.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack-dev-server": "^3.9.0"
},
"type": "module",
"devDependencies": {
"webpack": "^4.41.2"
},
"description": ""
}
As of Node 13.2.0+
Verify that you have the latest version of Node installed. Simply do one of the following:
Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
OR
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If you use an older Node version or have to
import statements are permitted only in ES modules.
For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to
add "type": "module" to package.json
add "--experimental-modules" flag to the node call

local modules node.js :can't load files other than index.js

I am trying to learn local module setup in my express js application.
test-module folder is created in my project folder and it contains two files
1)index.js
module.exports = {
indexfunc:function(){
console.log('ok from index');
}
}
2)hello.js.
module.exports = {
helloFunc:function(){
console.log('ok from hello');
}
}
importing this module in app.js file
var mymodule = require('hello-module');
console.log(mymodule);
output:{ indexfunc: [Function: indexfunc] }
But this returns console.log(require('hello-module').hello) undefined.
package.json for this module
{
"name": "hello-module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Since hello is a file in hello-module, you need to pass it as the path to require. Do:
console.log(require('hello-module/hello'))
By doing :
console.log(require('hello-module').hello)
You are printing the hello property exported by index.js
I addition to #Ayush answer, if your goal is to execute code from other files in a module folder you can export a reference like so :
//index.js
const helloModule = require('./hello');
module.exports = {
hello: helloModule,
indexfunc:function(){
console.log('ok from index');
}
}

Categories

Resources