'async_hooks' cant be found - javascript

I'm trying to bundle my js file with browserify and babel: browserify ./src/background.js > ./dist/bundle.js -t babelify
The full error message I get is: Error: Can't walk dependency graph: ENOENT: no such file or directory, lstat 'D:\prog\html\extvone\async_hooks' required by D:\prog\html\extvone\node_modules\on-finished\index.js
When I looked into on-finished\index.js I saw there was a require for require('async_hooks'), but async_hooks didn't lead to a .js file, or anything.
I tried installing all the packages to the same version with npm i and update NPM globally as mentioned here, and also intalling async_hooks with npm install.
Edit:
background.js first lines:
import PythonShell from 'python-shell';
const express = require('express');
const app = express();
package.json includes:
"dependencies": {
"express": "^4.18.2",
"python-shell": "^3.0.1"
},
"devDependencies": {
"#babel/core": "^7.20.5",
"#babel/preset-env": "^7.20.2",
"#types/express": "^4.17.14",
"babelify": "^10.0.0"
}
Versions are the following: Node -> 18.12.1 LTS 'express' -> 4.18.2
The 'express' module is the root of the problem. Without it - everything works smoothly.
Update:
As mentioned in the comments, I tried to use a node-only nodule in the browser. What I actually did is deleted all the dependency on it. In a more general note, I started using VITE instead of Browserify.

Related

React/node build error. Could not find a declaration file for module 'history'. 'node_modules/history/index.js' implicitly has an 'any' type

My project is suddenly having a build error. My current repo still has no problem, it only happens when I clone the repo to a new folder and install the package again then do npm run build.
So I am so scared to update the package right now...
I checked the merge history, I don't think any code merge should cause this issue..
Here is the error message I got:
$ npm run build
> container-client#2.32.0 build I:\ds\projects\new\container-service\client
> craco build
Creating an optimized production build...
Failed to compile.
I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx
TypeScript error in I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx(4,25):
Could not find a declaration file for module 'history'. 'I:/ds/projects/new/container-service/client/node_modules/history/index.js' implicitly has an 'any' type.
If the 'history' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/history` TS7016
2 | import './_index.scss';
3 | import store from '../../store';
> 4 | import { History } from 'history';
| ^
This is the package.json:
{
"private": false,
"dependencies": {
"axios": "^0.19.2",
"bootstrap": "^4.6.0",
"history": "^4.10.1",
"identity-obj-proxy": "^3.0.0",
"react": "~17.0.1",
"react-app-polyfill": "~2.0.0",
"react-dom": "~17.0.1",
"react-router-dom": "~5.2.0"
},
Looks like the library "history" is causing the problem.
I tried:
delete the node_module --> npm install --> npm run build --> same error
clone the project again --> npm install --> npm run build --> same error
clone the older version of the project --> npm install --> npm run build --> same error
Nothing seems to work.
Looks like the new history needs a dependency library #types/history. I did a npm i #types/history#4.7.9 and then did a npm i again. This fixed my problem.
the problem seems to be from the history package that you are using
Could not find a declaration file for module 'history'.
try installing types for the package
npm i #types/history
if that didn't work, then change the import to require
const history = require("history")
update
the #types/history is deprecated and since version 5 of history, the type declarations are provided inside the package itself.
updating the package should fix the issue:
npm install history#latest
Assuming its as common package you would install your package and the type declarations
npm install history
npm install --save-dev #types/history
and include the types in your project within the tsconfig compilerOptions -
typeRoots for where the compiler needs to look
types - the actual library names that can be found in typeRoots
"typeRoots": [
"./node_modules/#types"
],
"types": ["history"]

Import Class in Nodejs fail [duplicate]

I don't understand what is wrong.
Node v5.6.0
NPM v3.10.6
The code:
function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
The error:
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
Node 13+ Since Node 13, you can use either the .mjs extension, or set {"type": "module"} in your package.json. You don't need to use the --experimental-modules flag. Modules is now marked as stable in node.js
Node 12 Since Node 12, you can use either the .mjs extension, or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.
Node 9 In Node 9, it is enabled behind a flag, and uses the .mjs extension.
node --experimental-modules my-app.mjs
While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
See browser compat table on MDN and this Node issue.
From James M Snell's Update on ES6 Modules in Node.js (February 2017):
Work is in progress but it is going to take some time — We’re currently looking at around a year at least.
Until support shows up natively (now marked stable in Node 13+), you'll have to continue using classic require statements:
const express = require("express");
If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here's an example server.
Unfortunately, Node.js doesn't support ES6's import yet.
To accomplish what you're trying to do (import the Express module), this code should suffice
var express = require("express");
Also, be sure you have Express installed by running
$ npm install express
See the Node.js Docs for more information about learning Node.js.
I'm shocked esm hasn't been mentioned. This small, but mighty package allows you to use either import or require.
Install esm in your project
$ npm install --save esm
Update your Node Start Script to use esm
node -r esm app.js
esm just works. I wasted a TON of time with .mjs and --experimental-modules only to find out a .mjs file cannot import a file that uses require or module.exports. This was a huge problem, whereas esm allows you to mix and match and it just figures it out... esm just works.
As mentioned in other answers Node JS currently doesn't support ES6 imports.
(As of now, read EDIT 2)
Enable ES6 imports in node js provides a solution to this issue. I have tried this and it worked for me.
Run the command:
npm install babel-register babel-preset-env --save-dev
Now you need to create a new file (config.js) and add the following code to it.
require('babel-register')({
presets: [ 'env' ]
})
// Import the rest of our application.
module.exports = require('./your_server_file.js')
Now you can write import statements without getting any errors.
Hope this helps.
EDIT:
You need to run the new file which you created with above code. In my case it was config.js. So I have to run:
node config.js
EDIT 2:
While experimenting, I found one easy solution to this issue.
Create .babelrc file in the root of your project.
Add following (and any other babel presets you need, can be added in this file):
{
"presets": ["env"]
}
Install babel-preset-env using command npm install babel-preset-env --save, and then install babel-cli using command npm install babel-cli -g --save
Now, go to the folder where your server or index file exists and run using:
babel-node fileName.js
Or you can run using npm start by adding following code to your package.json file:
"scripts": {
"start": "babel-node src/index.js"
}
Error: SyntaxError: Unexpected token import or SyntaxError: Unexpected token export
Solution: Change all your imports as example
const express = require('express');
const webpack = require('webpack');
const path = require('path');
const config = require('../webpack.config.dev');
const open = require('open');
And also change your export default = foo; to module.exports = foo;
In case that you still can't use "import" here is how I handled it:
Just translate it to a node friendly require. Example:
import { parse } from 'node-html-parser';
Is the same as:
const parse = require('node-html-parser').parse;
babel 7 proposal
can you add dev dependencies
npm i -D #babel/core #babel/preset-env #babel/register
and add a .babelrc in the root
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
and add to the .js file
require("#babel/register")
or if you run it in the cli, you could use the require hook as -r #babel/register, ex.
$node -r #babel/register executeMyFileWithESModules.js
When I was started with express always wanted a solution to use import instead require
const express = require("express");
// to
import express from "express"
Many time go through this line:- Unfortunately, Node.js doesn't support ES6's import yet.
Now to help other I create new two solutions here
1) esm:-
The brilliantly simple, babel-less, bundle-less ECMAScript module loader.
let's make it work
yarn add esm / npm install esm
create start.js or use your namespace
require = require("esm")(module/*, options*/)
// Import the rest of our application.
module.exports = require('./src/server.js')
// where server.js is express server start file
Change in your package.josn pass path of start.js
"scripts": {
"start": "node start.js",
"start:dev": "nodemon start.js",
},
"dependencies": {
+ "esm": "^3.2.25",
},
"devDependencies": {
+ "nodemon": "^1.19.2"
}
2) Babel js:-
This can be divide into 2 part
a) Solution 1 thanks to timonweb.com
b) Solution 2
use Babel 6 (older version of babel-preset-stage-3 ^6.0)
create .babelrc file at your root folder
{
"presets": ["env", "stage-3"]
}
Install babel-preset-stage-3
yarn add babel-cli babel-polyfill babel-preset-env bable-preset-stage-3 nodemon --dev
Change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build"
},
"devDependencies": {
+ "babel-cli": "^6.26.0",
+ "babel-polyfill": "^6.26.0",
+ "babel-preset-env": "^1.7.0",
+ "babel-preset-stage-3": "^6.24.1",
+ "nodemon": "^1.19.4"
},
Start your server
yarn start / npm start
Oooh no we create new problem
regeneratorRuntime.mark(function _callee(email, password) {
^
ReferenceError: regeneratorRuntime is not defined
This error only come when you use async/await in your code.
Then use polyfill that includes a custom regenerator runtime and core-js.
add on top of index.js
import "babel-polyfill"
This allow you to use async/await
use Babel 7
Need to upto date every thing in your project
let start with babel 7
.babelrc
{
"presets": ["#babel/preset-env"]
}
Some change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build",
....
}
"devDependencies": {
+ "#babel/cli": "^7.0.0",
+ "#babel/core": "^7.6.4",
+ "#babel/node": "^7.0.0",
+ "#babel/polyfill": "^7.0.0",
+ "#babel/preset-env": "^7.0.0",
+ "nodemon": "^1.19.4"
....
}
and use import "#babel/polyfill" on start point
import "#babel/polyfill"
import express from 'express'
const app = express()
//GET request
app.get('/', async (req, res) {
// await operation
res.send('hello world')
})
app.listen(4000, () => console.log('🚀 Server listening on port 400!'))
Are you thinking why start:dev
Seriously. It is good question if you are new. Every change you are boar with start server every time
then use yarn start:dev as development server every change restart server automatically for more on nodemon
if you can use 'babel', try to add build scripts in package.json(--presets=es2015) as below. it make to precompile import code to es2015
"build": "babel server --out-dir build --presets=es2015 && webpack"
As of Node.js v12 (and this is probably fairly stable now, but still marked "experimental"), you have a couple of options for using ESM (ECMAScript Modules) in Node.js (for files, there's a third way for evaling strings), here's what the documentation says:
The --experimental-modules flag can be used to enable support for
ECMAScript modules (ES modules).
Once enabled, Node.js will treat the following as ES modules when passed to
node as the initial input, or when referenced by import statements within
ES module code:
Files ending in .mjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"module".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=module.
Node.js will treat as CommonJS all other forms of input, such as .js files
where the nearest parent package.json file contains no top-level "type"
field, or string input without the flag --input-type. This behavior is to
preserve backward compatibility. However, now that Node.js supports both
CommonJS and ES modules, it is best to be explicit whenever possible. Node.js
will treat the following as CommonJS when passed to node as the initial input,
or when referenced by import statements within ES module code:
Files ending in .cjs.
Files ending in .js, or extensionless files, when the nearest parent
package.json file contains a top-level field "type" with a value of
"commonjs".
Strings passed in as an argument to --eval or --print, or piped to
node via STDIN, with the flag --input-type=commonjs.
I'm going to address another problem within the original question that no one else has. After recently converting from CommonJS to ESM in my own NodeJS project, I've seen very little discussion about the fact that you cannot place imports wherever you want, like you could with require. My project is working great with imports now, but when I use the code in the question, I first get an error for not having a named function. After naming the function, I receive the following...
import express from 'express'
^^^^^^^
SyntaxError: Unexpected identifier
at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
You cannot place imports inside functions like you could require. They have to be placed at the top of the file, outside code blocks. I wasted quite a bit of time on this issue myself.
So while all of the above answers are great at helping you get imports to work in your project, none address the fact that the code in the original question cannot work as written.
import statements are supported in the stable release of Node since version 14.x LTS.
All you need to do is specify "type": "module" in package.json.
In my case it was looking after .babelrc file, and it should contain something like this:
{
"presets": ["es2015-node5", "stage-3"],
"plugins": []
}
My project uses node v10.21.0, which still does not support ES6 import keyword. There are multiple ways to make node recognize import, one of them is to start node with node --experimental-modules index.mjs (The mjs extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require in your code. If there is need to use both nodejs's require keyword along with ES6's import, then the way out is to use the esm npm package. After adding esm package as a dependency, node needs to be started with a special configuration like: node -r esm index.js
I've been trying to get this working. Here's what works:
Use a recent node version. I'm using v14.15.5. Verify your version by running: node --version
Name the files so that they all end with .mjs rather than .js
Example:
mod.mjs
export const STR = 'Hello World'
test.mjs
import {STR} from './mod.mjs'
console.log(STR)
Run: node test.mjs
You should see "Hello World".
Simply install a higher version of Node. As till Node v10 es6 is not supported. You need to disable a few flags or use

How can I incorporate JS libraries into my NPM build script?

My current site is build with html+css (scss) and using a NPM build script (see below). I now want to add a few JS libraries to my website (for example: lozad).
So far I've downloaded the dependencies for it. As I'm not familiar with JS, I don't understand the other steps I need to take. I tried following the documentation but it's not working so far.
I now assume that this is because my current NPM build script doesn't track JS, so any JS wouldn't be shown on my devserver. So maybe it did work, but just not in test?
Can anyone point me in the direction of what I need to do to make it working, and/or how to update my NPM script?
"scripts": {
"watch:sass": "node-sass sass/main.scss css/style.css -w",
"devserver": "live-server --browser=firefox",
"start": "npm-run-all --parallel devserver watch:sass",
"compile:sass": "node-sass sass/main.scss css/style.comp.css",
"concat:css": "concat -o css/style.concat.css css/icon-font.css css/style.comp.css",
"prefix:css": "postcss --use autoprefixer -b 'last 10 versions' css/style.concat.css -o css/style.prefix.css",
"compress:css": "node-sass css/style.prefix.css css/style.css --output-style compressed",
"build:css": "npm-run-all compile:sass concat:css prefix:css compress:css"
},
"devDependencies": {
"autoprefixer": "^9.6.0",
"concat": "^1.0.3",
"node-sass": "^4.12.0",
"npm-run-all": "^4.1.5",
"postcss-cli": "^6.1.2",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.6"
},
"dependencies": {
"aos": "^2.3.4",
"lozad": "^1.9.0",
}
}
You just need to give the relative path to the dependency and run the script like so:
"scripts": {
...
"lozad": "npm run ./node_modules/lozad/index.js --argument"
}
Note that this is only assumed data. The real path and file are probably called something else (Just look into the node:modules folder for lozad).
According to this article, you can also omit the path and the npm rum when there is a .bin folder for that dependency, but I have not tested that.
Edit
In case you meant on how to use the library locally.
You have to add the package to your dependencies (Like you did) and then call
npm install
in your project directory. It will install all your dependencies specified in package.json.
You can omit the manual "add dependency to file" step by simply calling:
npm install --save lozad
After that you can use it in your project like so:
// using ES6 modules
import lozad from 'lozad'
// using CommonJS modules
var lozad = require('lozad')
If you don't know which one to use, just try them - your IDE will tell you if something is wrong.
When you imported the library, you can use it like described at the Usage Description.

Unexpected token export when running Terminal App

This seems like just a normal module and export, not sure what's causing this.
myES6Module.js
const showCar = () => {
//...code
}
const drive = () => {
//...code
};
drive();
export { drive, showCar }
What's weird is in my tests I'm able to import and call these just fine and my tests use them and pass. But when I actually run the drive() which runs the app by prompting the user for terminal input, I get an error saying:
SyntaxError: Unexpected token export
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Proxy.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
Why would this resolve just fine for test but not live running of the code?
Here's how I'm running it, a script in my package.json:
"start": "node --experimental-modules ./myES6Module.js"
so it's when I run yarn start I get this. Otherwise, when I run my tests, drive() outputs to the console just fine.
if I comment out that exports, my script runs fine...but of course that breaks my tests which rely on exporting stuff.
UPDATE
I'm using --experimental-modules
So I tried this since I have babel-cli installed:
"start": "babel ./myES6Module.js"
package.json has the following babel packages:
"#babel/cli": "^7.0.0-beta.51",
"#babel/preset-env": "^7.0.0-beta.51",
"#babel/register": "^7.0.0-beta.51",
"#babel/core": "^7.0.0-beta.51",
but that just console.logged the file content, it didn't run it.
I don't want to use --experimental-modules either. I don't want to change my file extension so how do I get this running?
I took a look at this and it mentions about migrating if you are already using babel-node but is that the only way?
https://babeljs.io/docs/en/next/v7-migration
To answer your initial question, you need to have the file extension for the files to be .mjs so that you can define in your package.json scripts:
"start": "node --experimental-modules myES6Module.mjs"
The second part about removing the --experimental-modules flag as you noted just logged out the file contents when using babel. To get around this you can use babel-node but note its warning on use in production. In that warning you will find a link to Example Node Server w/ Babel demonstrating a working solution.
To produce the results you are after I've created a minimum working solution with the following which is working for me:
npm i babel-cli babel-preset-es2015
Update your package.json to:
"start": "babel-node --presets es2015 myES6Module.js"
And a working .js file using export:
const showCar = () => {
//...code
}
const drive = () => {
//...code
console.log('driving')
};
drive();
export { drive, showCar }
Babel 7
If you want to use version 7 then try below.
npm i #babel/cli #babel/core #babel/node #babel/preset-env so your package.json has the below dependencies:
"#babel/cli": "^7.0.0-beta.51",
"#babel/core": "^7.0.0-beta.51",
"#babel/node": "^7.0.0-beta.51",
"#babel/preset-env": "^7.0.0-beta.51"
Set the run script to
"start": "babel-node myES6Module.js"
Create a .babelrc file at the root level of your project with
{
"presets": ["#babel/preset-env"]
}
Now you can execute npm run start from the terminal and you should see the output driving logged to the terminal based on my example code.
I haven't used version 7 before and the docs say that the .babelrc file should use "presets": ["env"] but I got an error, however the above and "presets": ["#babel/env"] worked the same. Someone else might know the reasoning behind this error I ran into but that's for another question.

Vue.js browserify Cannot find module

With almost every npm package that I'm trying to use with vue.js 1.0 I receive this error:
{ Error: Cannot find module '!!./../../../node_modules/css-loader/index.js!./../../../node_modules/vue-loader/lib/style-rewriter.js!./../../../node_modules/vue-loader/lib/selector.js?type=style&index=0!./dashboard.vue' from '/Users/jamie/Code/forum/node_modules/vue-html5-editor/dist'
at /Users/jamie/Code/forum/node_modules/resolve/lib/async.js:46:17
at process (/Users/jamie/Code/forum/node_modules/resolve/lib/async.js:173:43)
at ondir (/Users/jamie/Code/forum/node_modules/resolve/lib/async.js:188:17)
at load (/Users/jamie/Code/forum/node_modules/resolve/lib/async.js:69:43)
at onex (/Users/jamie/Code/forum/node_modules/resolve/lib/async.js:92:31)
at /Users/jamie/Code/forum/node_modules/resolve/lib/async.js:22:47
at FSReqWrap.oncomplete (fs.js:117:15)
It drives me nuts! I'm using vue.js with browserify. Looked everywhere on the web:
https://github.com/webpack/css-loader/issues/240
https://github.com/webpack/css-loader/issues/180
https://github.com/webpack/css-loader/issues/295
https://github.com/webpack/css-loader/issues/163
Nothing seems to work! What am I doing wrong!?
2 packages where I've this problem:
https://github.com/lian-yue/vue-upload-component/
https://github.com/PeakTai/vue-html5-editor
My gulpfile:
const elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
require('laravel-elixir-stylus');
elixir(mix => {
mix.browserify('main.js');
mix.styles([
'./node_modules/normalize-css/normalize.css',
'./node_modules/nprogress/nprogress.css',
'./node_modules/sweetalert/dist/sweetalert.css',
]);
mix.stylus('app.styl');
});
A solution would really help me out.
--EDIT--
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"gulp": "^3.9.1",
"laravel-elixir": "^6.0.0-9",
"laravel-elixir-browserify-official": "^0.1.3",
"laravel-elixir-stylus": "^2.0.3",
"vue-html5-editor": "^0.5.1"
},
"dependencies": {
"browserify": "^13.1.0",
"laravel-elixir-vueify": "^2.0.0",
"normalize-css": "^2.3.1",
"nprogress": "^0.2.0",
"stylus": "^0.54.5",
"sweetalert": "^1.1.3",
"vue": "^1.0.26",
"vue-resource": "^0.9.3",
"vue-router": "^0.7.13",
"vue-spinner": "^1.0.2",
"vue-upload-component": "^2.0.0-beta"
}
}
Those are webpack packages and you are using browserify. If you need to use webpack packages you should be using webpack as your bundler.
I did have a go at installing the vue-upload-component package to see how easy it would be with browserify and elixir but it's awkward to say the least. I didn't get it working because it uses babel transforms to compile the vue files, so first you need to pull them in manually and then you would likely need to write an elixir extension to use those transforms to get it to work. Obviously each webpack package will be different so you would need to do that each time you install one, which is hardly convenient.
I had some luck changing the configuration output of the Vue component I wanted to use to use webpack -p instead of just webpack.
I could then take that output without the hot module code and put it through browserify:
browserify file.js --standalone SomeLibrary > file.browser.js
Where file.js is the webpack -p output, SomeLibrary is the name you want on the global window scope from the browserify packaging, and file.browser.js is your resultant file to include in your project.

Categories

Resources