Upgrade js file to use import - javascript

I'm trying to upgrade to use import instead of requires for modules:
My old code looked like so:
const { NETWORK } = require(`${basePath}/constants/network.js`);
The network.js File:
export const NETWORK = {
eth: "eth",
sol: "sol",
};
module.exports = {
NETWORK,
};
When ever I try to import i've tried a few syntaxes):
import { NETWORK } from '../constants/network.js';
import NETWORK from '../constants/network.js';
import * as NETWORK from '../constants/network.js';
I get an error:
This file is being treated as an ES module because it has a '.js' file extension and '..\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///../constants/network.js:6:1
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
When I try to rename the file to be network.cjs I get an error:
SyntaxError: Unexpected token 'export'
how can I import variables from js files using import?

You need to remove the unnecessary "module.exports" part from your network.js, because that is the way to export stuff in commonjs. Your first line of import will work after that import { NETWORK } from '../constants/network.js'; so remove the other ones

Related

node: getting error importing CommonJS module however I try to import it

I have a local node module, #em/inVis in my company whose index.d.ts file looks as follows:
import UWeb from "./UWeb";
import UWebParams from "./UWebParams";
export { UWeb, UWebParams };
elsewhere within the app, it's used as follows in typescript files
import { UWeb, UWebParams } from "#em/inVis";
when I try to do that in my TS file, I get the node error:
SyntaxError: Named export 'UWeb' not found. The requested module '#em/inVis' is a CommonJS module, which may not support all
module.exports as named exports. CommonJS modules can always be
imported via the default export, for example using:
import pkg from '#em/inVis'; const { UWeb, UWebParams } = pkg;
so when I try using that approach suggested above, I am getting the node error:
SyntaxError: Cannot use import statement outside a module not sure
what I am doing wrong.

Cannot use import statement outside a module although type is module

I'm using ES6 style and want to be consistent of using import from ES6.
Here is my jest test file I'm setting up:
import Get from './Get'
test('Some test', async () => {
expect(true).toBe(true)
})
And here is my Get file:
import cli from "commander";
import get from "./myHandler.js"
const GET = () => {
// Doing some stuff here...
}
export default GET
I keep getting:
C:\...\GET\get.test.js:2
import Get from './Get';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1773:14)
And I have already added "type": "module", in my package.json as suggested by this and others. What am I doing wrong here?

Node Error: Cannot use import statement outside a module even though I'm not

I am using Pm2 and this is the error:
SyntaxError: Cannot use import statement outside a module
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
The issue is, the package.json is already set to "type": "module".
Also, everything used to work fine until I restart the server.
Here is the actual .js file:
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const hostname = 'localhost';
const port = 8080;
import captureWebsite from 'capture-website';
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
....
});
If the require calls are not throwing an error, the "actual .js file" creating the http server in the post is being treated as CommonJS. But CommonJS code can't use import statements and needs to use import expressions instead (see node and MDN docs).
If you use dynamic imports ( which are asynchronous) you would also need to use the imported module after an await statement (inside an async function), or in a success handler provided in a then method:
// ....
import('capture_website')
.then( capture_website => {
// code requiring existence of `capture_website`
})
.catch( err=> console.error("Import of capture_website failed", err));
However you can import CommonJS modules using an import statement in ES6 files (Node doc).
Hence a better solution may be to rename the main js file posted to give it a .mjs extension, and replace all the require statements in the file with import statements:
import http from 'http';
import url from 'url';
import querystring from 'querystring';
This gets rid of the Cannot use import statement outside a module syntax error. Imported modules that are CommonJS should still be able to require modules using the require function.

How to correct: SyntaxError: Named export 'mongo' not found

Trying to run a simple script to create a user with mongoose using nodejs. So basically just running node my_script.js which is the official way as per Run Node.js scripts from the command line
I have tried importing in the following ways:
import Connection from 'mongoose';
const { mongo } = Connection;
import mongoose from "mongoose"
import mongoose from "node_modules/mongoose/index.js"
const mongoose = require("mongoose")
Also tried adding the following lines to package.json:
"type": "module",
"esModuleInterop": true,
Complete error seen below for most of the import cases above:
import mongoose, { mongo } from "mongoose";
^^^^^
SyntaxError: Named export 'mongo' not found. The requested module 'mongoose' is a CommonJS module, which may not support all module.exports as named exports.CommonJS modules can always be imported via the default export, for example using:
import pkg from 'mongoose';
const { mongo } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:98:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:143:5)
at async Loader.import (internal/modules/esm/loader.js:165:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
From mongoose index.js file I do not see any other export besides:
const mongoose = module.exports = exports = new Mongoose({
[defaultMongooseSymbol]: true
});
Found this github issue Misleading error that module does not provide export
#32137 but still not sure how to make this import to work.
This "appears" to be the fix which is the only thing that happened after I took a break.
I had 2 files: B.js and A.js
from A.js:
import foo from "./B.js";
import mongoose from "mongoose";
I decided to run B.js on it's own to see if it would give me the same error(it had a mongoose import as well), it turn's out there was another different error:
foo.pre(save, function(next) {
^ ReferenceError: save is not defined
Ok nothing biggy, corrected it and node B.js worked fine when running it, hence decided to test with node A.js, which worked just fine to my surprise!
This turned out to be completely counterintuitive, as the error mentioned initially was not pointing to this.

Rollupjs Leave imports unchanged

My input file looks like this:
import * as chalk from 'chalk'
const chalkInstance = new chalk.Instance({
level: 1
})
My output file looks like this:
import { Instance } from 'chalk';
const chalkInstance = new Instance({
level: 1
});
The problem is that chalk is a commonjs module and I want to my output to be an es module so when I execute the file I get the following error: The requested module 'chalk' is expected to be of type CommonJS, which does not support named exports etc. Is there a way to prevent Rollup from changing the import * as something imports? The problem doesn't go away even if I disable treeshaking.
Thank you in advance!
Preserving the import as typed won't help you — you need to do import chalk from 'chalk' instead, since CommonJS modules only have a default export. If you do preserve the import you'll still get an error, it'll just be a different error:
const chalkInstance = new chalk.Instance({
^
TypeError: chalk.Instance is not a constructor

Categories

Resources