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

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.

Related

Trouble importing the "uuid" npm package. TypeError: Relative references must start with either "/", "./", or "../"

I am trying to import a module called "uuid" to my index.js script which I installed through this command: npm install uuid.
First I tried using CommonJS syntax, but that gave me this error: Uncaught ReferenceError: require is not defined
const { v4: uuidv4 } = require('uuid');
// ReferenceError: require is not defined
My IDE recommended that I convert my file to an ES module instead:
import { v4 as uuidv4 } from 'uuid';
// SyntaxError: Cannot use import statement outside a module
By adding type="module" to my index.js script in the html only produces new errors:
TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".
I have searched for a while now but can't find anything. Upon trying to follow the error message instructions I try to generate a more direct path to the "uuid" module like this:
import { v4 as uuidv4 } from '../node_modules/uuid/dist/v4';
// GET http://localhost:3000/node_modules/uuid/dist/v4 net::ERR_ABORTED 404 (Not Found)
Even with this direct path it can't find the module which is weird as it is at least recognizing something when only specifying the module name "uuid".
If it's to any help here is my package.json dependencies
"dependencies": {
"express": "^4.18.1",
"nodemon": "^2.0.20",
"socket.io": "^4.5.2",
"socket.io-client": "^4.5.4",
"uuid": "^9.0.0"
}
You're trying to import uuid module from node_modules in the script running in the browser. Unfortunately, it's that simple. The node_modules work for Node.js only, browsers don't know about them.
There are multiple ways you can fix this:
Setup a static server that will serve uuid. Then, you can import it by its url (e.g import { v4 as uuidv4 } from './uuid';). This is generally not recommended.
Use CDN. It's similar to the previous method, but this time someone will set up a static server for you. This is often used in production because of good performance, and you don't need to do anything for this. It's simple: import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
But not all libraries are hosted on CDNs. Also, you'd probably need to optimize your dependencies and code. So for complex applications, you should use a so called bundler. Here are a few of the most popular: Vite, Rollup, Webpack, Parcel. What bundlers do: they analyze your imports and then produce a single js file called an "entrypoint". Depending on configuration they can combine all dependencies into one file, or insert special code that will dynamically import your dependencies from other files when they are needed for code to execute.

import module without nodejs - vanillaJS

I'm refreshing my old and low knowledge on VanillaJS using the latest best practices i found.
I recently did a tutorial on NodeJS doing API REST with ExpressJs and one with Socket IO.
Now I want to practice a little before going to REACTJS.
So I started a little project
I do one without NodeJs - just JS into HTML view - using Objects.
I want to use modules from Npm. I want to try Fakerjs but when i want to import it i have a 403.
The path is correct, no error.
So i'm wondering if it's possible without Nodejs to import modules when doing VanillaJs?
Am i doing it wrong ?
The structure of the project is :
js/
main.js
class/
node_modules/
index.html
Main.js:
'use strict'
//Importation of modules
import faker from '../node_modules/faker'
//Importation of Class Folder
import { Crypto } from "./class/crypto.class.js";
console.log(faker);
faker.locale = 'en_US';
I have this error in console:
GET http://crypto-market-js.local:8282/node_modules/faker/ net::ERR_ABORTED 403 (Forbidden)
If i write : import faker from 'faker' (like with node js but it's a require instead) i have this : Uncaught TypeError: Failed to resolve module specifier "faker". Relative references must start with either "/", "./", or "../".
If you could give me a hand on that plz :)
Trying to import with require is not supported without NodeJS, because require is a node-specific function. When trying to import modules into Vanilla JS, my recommendation is to first link to ths script with the <script> html tag, and then add another script with import faker from 'faker'
Hope that clarifies your issue.

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.

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

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.

Import module in React component for publish on NPM

It's my first React component for publication in NPM. I use react-webpack-component package from Yeoman to start my project. But when I install and import my component to React app, I catch error:
Failed to compile.
Error in ./~/kladrapi-react/index.js
Module not found: [CaseSensitivePathsPlugin] `/develop/myproject/node_modules/kladrapi-react/node_modules/React/react.js` does not match the corresponding path on disk `react`.
# ./~/kladrapi-react/index.js 1:82-98
I'm understand this error, but not understand how correctly import React modules to my component!
Actual version on GitHub
I think there are multiple issues in your code.
In index.html:
#line-- <script src="kladrapi-react.js"></script>
The file name is "kladrapi-react.jsx" not "kladrapi-react.js".
Second issue, here you are expecting "kladrapi-react.js(x)" to be on root level. Which is not the case. According to your folder structure "kladrapi-react.js(x)" file is at ./lib/kladrapi-react.jsx.
Apart from this, in your kladrapi-react.js(x) file you have mixed ES5 and ES6 syntax. You are accessing the variable KladrapiReact in index.html but you haven't exported it as 'KladrapiReact'. I would recommend you to put 'React.createClass....' code in a separate component.
For the error you are receiving you need to use 'case-sensitive-paths-webpack-plugin':
This Webpack plugin enforces the entire path of all required modules match the exact case of the actual path on disk.
npm install --save-dev case-sensitive-paths-webpack-plugin
Usage:
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var webpackConfig = {
plugins: [
new CaseSensitivePathsPlugin()
// other plugins ...
]
// other webpack config ...
}
For more info on this plugin read documentation here.
Module not found: [CaseSensitivePathsPlugin] /develop/myproject/node_modules/kladrapi-react/node_modules/React/react.js does not match the corresponding path on disk react.
# ./~/kladrapi-react/index.js

Categories

Resources