How to import nodejs module "module" via es6 import to create "require" function with "createRequire" in order to use node's "require"? - javascript

I am writing a JavaScript es6 module which contains "Mocha" test-cases which test a JavaScript es6 module containing the actual functionality of my app.
I am trying to import nodejs module "module" via es6 import like so:
import { createRequire } from 'module';
Next I create a "require" function by calling "createRequire":
const require = createRequire(import.meta.url);
Afterwards I try to use "require" to import nodejs modules:
const chai = require('chai');
const assert = chai.assert;
I put that all together in a HTML file, started a web-server and opened the HTML file in the browser.
Unfortunately, the first line gives me an error in the console of the Browser Firefox:
TypeError: Error resolving module specifier: module
The browser Chromium gives me the following error message:
Uncaught TypeError: Failed to resolve module specifier "module". Relative references must start with either "/", "./", or "../".
Actually, giving relative references is not working either:
I installed the nodejs module "module" (npm install module) and used a relative path to that module. Unfortunately, the browser does not know how to load the module because no concrete entrypoint is given.
I just tried stick to the manual but had no luck:
https://nodejs.org/api/modules.html#modules_module_createrequire_filename
What do you think? How should I change my code so that this works?
Many thanks in advance for your valuable advice.

I hope you've installed the module using 'npm install module' command, try using commonJS pattern and include the module in the following way
const { createRequire } = require('module');

require() is used to load files in node, and module is a node module.
These things don't exist in browsers.
You do these things, and running mocha tests in node. There should be no browser, just a command line.

Related

Why am I getting this UnhandledPromiseRejectionWarning error when running npm build on my serverless project?

I am getting the following error when trying to run npm build on my serverless aws-nodejs-typescript project and do not understand how to fix it. Anyone able to point me in the right direction please?
npm build
(node:44390) UnhandledPromiseRejectionWarning: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /usr/local/lib/node_modules/npm/node_modules/chalk/source/index.js
require() of ES modules is not supported.
require() of /usr/local/lib/node_modules/npm/node_modules/chalk/source/index.js from /usr/local/lib/node_modules/npm/lib/utils/explain-dep.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /usr/local/lib/node_modules/npm/node_modules/chalk/package.json.
...
Thanks very much!
The latest version of chalk has changed to ES6 import/export syntax instead of CJS (CommonJS with require). So instead of:
const chalk = require('chalk');
You have to do:
import chalk from 'chalk';
You'll (unfortunately) have to change all the other requires into imports as well, then change all your module.exports into export default and all your exports.whatever to export whatever; where whatever is your thing, or as suggested rename your file to index.cjs to force CJS.
Then there are the docs for import and export if you need them.
Then, you need to add type: "module" to package.json. So much for chalk :)
I didn't like that so I used to just use colors intead, but...

Cannot import Node, JS, or Electron library in Angular Typescript module no matter what I try

I'm fairly new to stack overflow, so if I don't ask the question correctly feel free to help me out.
I've scoured every stack overflow and google article I can find and nothing works to import Electron, any other Node modules, or any native JS modules--I can only import and use Angular/typescript modules. I'm trying to import electron and use it in an angular app. I am also trying to use __dirname. For electron I've tried:
const { remote } = require('electron');
const { remote } = (<any>window)require('electron');
import { ipcRenderer, BrowserWindow, electron } from 'electron';
import * as remote from '#electron/remote'
For __dirname I've tried:
import * as fs from 'fs';
import { readFileSync } from 'fs';
import readFileSync from 'fs';
and for the implementation:
import.meta.url
process.cwd()
__dirname //worth a shot I guess
I've combined these options, and nothing works. I've run npm install --save-dev #types/node, and when that didn't work tried deleting the node_modules folder and ran npm install. "types": ["node"] has already been added to tsconfig.json's compilerOptions.
Here is one of my errors:
Error: src/app/electron/electron.service.ts:3:20 - error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev #types/node` and then add `node` to the types field in your tsconfig.
3 const { remote } = require('electron');
~~~~~~~
I've already installed #types/node. It also almost always posts the following error. I have no clue what it's for, as it shows even when I'm not importing 'fs'.
Error: ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/user/Programming/Git/project/node_modules/electron'
resolve 'fs' in '/Users/user/Programming/Git/project/node_modules/electron'
Parsed request is a module
using description file: /Users/user/Programming/Git/project/node_modules/electron/package.json (relative path: .)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
looking for modules in /Users/user/Programming/Git/project
using description file: /Users/user/Programming/Git/project/package.json (relative path: .)
Your browser cannot run modules written in C++ like fs and electron. Node.js can do it because node developers specifically created node to be able to load binary modules (written in C++). Browsers can only run javascript modules.
As such builders such as Webpack ignore these modules simply because it does not make sense to include them.
You cannot use fs and electron in your Angular app. You can however use Angular in your electron app (because electron was created to run javascript code and Angular compiles to pure javascript code).
Trying to use fs or electron in Angular is a little bit like trying to import Internet Explorer or Adobe Photoshop in Angular.

Node can't find modules without .js extension

I have a file, test.js with these lines of code inside:
import {blabla} from "./bla";
async function dataGenerator() {
..........
}
(async() => {
console.log('1')
await dataGenerator()
console.log('2')
})()
Note: Ignore the import structure. It is just fictive for the question. In my file the imports are auto.
When I'm trying to run from terminal with node test.js it returns error:
Cannot find module 'D:\bla' imported from D:\test.js
I have added into package.json the line: "type": "module". Without this it returns:
Cannot use import statement outside a module
I'm using node v14. How can I run the test.js without adding to all the imports ".js". There are functions in functions in functions and is complicated to add .js extension. Is there any npm to run it?
Node.js by default does not attempt to guess the file extension when using import for ES modules. This is different from CommonJS modules with require.
In the documentation for the ES module loader you can read how files are found on disk.
The heading 'Customizing ESM specifier resolution algorithm' states:
The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm. The default mode is explicit, which requires the full path to a module be provided to the loader. To enable the automatic extension resolution and importing from directories that include an index file use the node mode.

Import ES6 module from http url in Typescript

I am writing an ES6 module which depends on the other ES6 module specified with http url like this:
import { el, mount } from "https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js";
const pElem = el("p") // definitely works in Javascript
When I tried to translate my module in Typescript, I got this error:
Cannot find module 'https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js' or its corresponding type declarations.
I'm using ts-watch npm module to compile Typescript, and it works fine unless I don't use the import from https://....
I also know that if I tried to import npm module (e.g. import {el} from "redom") it works as well. But what I am writing is a module for web browser, not that of npm. With this reason, using webpack is not an option.
Thanks to #acrazing's comment, I managed to resolve this problem. Here's how:
In a new ts file:
declare module 'https://*'
This mutes the error that Typescript compiler attempts to read type declaration.
If you want to access type declaration as a node dependency, paste this in a new ts file:
declare module 'https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js' {
export * from 'redom'
}
and add redom dependency in package.json
"dependencies": {
"redom": "3.26.0",
...
},
Then, type declaration is read from local ./node_modules directory, VSCode recognizes the types as well.
declare module 'https://*' somehow doesn't work for me so I simply ignore it.
// #ts-ignore Import module
import { Foo } from "https://example.com/foo.ts";
// Now you can use Foo (considered any)

Typescript compile with imports

So I have two files: a.ts and b.ts. b exports something for a to use. The TypeScript compiler handles this fine, but refuses to create valid output for a browser. Example:
import { test } from "./b";
console.log(test);
b.ts
export const test = "quest";
and now I try compiling it:
$ tsc --lib dom,es2018 --target ES2018 --out test.js a.ts b.ts
b.ts:1:1 - error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
1 export const test = "quest";
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.
hm, weird. Okay, let's try using --module. If I use amd a browser that loads test.js will tell me: ReferenceError: define is not defined. If I try system it says: ReferenceError: System is not defined.
Okay, that's not working. Let's try without setting a single output file with --out. That gives me:
SyntaxError: import declarations may only appear at top level of a module a.js:1
SyntaxError: export declarations may only appear at top level of a module b.js:1
So based on this, it seems like my only options for using typescript are:
Put all code in a single file
Use an external library like require.js or webpack
Learn what a module is and if/how it can be used in a browser
Or am I missing something? How do I compile Typescript using imports without adding libraries/modules ?
TypeScript version: 3.8.3
Syntax error
please correct this
export const test = "quest";
to
export test = "quest";
No need to add any const here while exporting

Categories

Resources