nodejs Import require conversion - javascript

Learning NodeJs here. Problem is when I tried to search for answers, I am not finding what I am looking for. Probably because this is too basic or non-issue.
I am working on nodejs with angular2. So naturally, I have things like:
import { stuff } from 'some_module'
But I am trying to work with a package that has usage example of:
var stuff = require('some_module')
Obviously, my code didn't work when I use import etc. else I wouldn't be posting here. Is it because I am doing something wrong? Or am I out of luck such that this particular module doesn't work with import? Can someone shed some light on how to write proper import statements when I see usage sample of require('some_stuff'), so I can use other modules I download from npm?
thanks in advance.
EDIT:
So I tried npm install requirejs --save. Then I wrote the require statement above. But I am getting a 404 on the package...

You can use import but you have to run your app with babel.
you have to add this line to your package.json file
"scripts": {
"start": "NODE_ENV=production node_modules/.bin/babel-node --presets 'es2015' src/server.js",
"build": "NODE_ENV=production node_modules/.bin/webpack -p"
},
"dependencies": {
"babel-cli": "^6.11.4",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.13.2"
},
"devDependencies": {
"http-server": "^0.9.0",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.14.1"
}
src/server.js file is your main file location
and then run file with following command
npm run start
when you use import { stuff } from 'module';
then you can directly use stuff() in your program.
but when you use var stuff = require('module');
then you need to do stuff.stuff() in your program.

It's interesting that the original syntax
var stuff = require('some_module')
is not working for you. If your app was scaffolded from Angular CLI then it should support both imports and require statements out of the box.
for example, I'm using MSR in an Angular 2 component like this:
var MediaStreamRecorder = require('msr');

Related

Typescript: Debug Failure. False expression: Non-string value passed to `ts.resolveTypeReferenceDirective`

I've an npm command line application that i've built not so long ago and it worked fine. Now that i've updated it, and due to changes in the versions of typescript over the period, i'm getting an error when i want to run this package which says:
Debug Failure. False expression: Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.
Here is the package.json file:
{
"name": "initialiseur",
"version": "4.0.4",
"main": "src index.ts",
"author": "#crispengari",
"license": "MIT",
"bin": "src/index.ts",
"description": "THIS IS A BOILER PLATE THAT INITIALIZE A NODE EXPRESS BACKEND FOR TYPESCRIPT AND JAVASCRIPT",
"scripts": {
"watch": "tsc -w",
"start": "ts-node src/index.ts",
"dev": "nodemon dist/index.ts",
"start:fast": "tsnd --respawn src/index.ts"
},
"dependencies": {
"#types/inquirer": "^7.3.3",
"#types/node": "^17.0.42",
"#types/npm": "^7.19.0",
"chalk": "^4.1.2",
"cors": "^2.8.5",
"cross-fetch": "^3.1.5",
"dotenv": "^10.0.0",
"inquirer": "^8.1.2",
"node-fetch": "^3.2.6",
"octokit": "^1.7.2",
"ts-node": "^10.8.1",
"typescript": "^4.6.5"
},
"devDependencies": {
"#types/node-fetch": "^2.6.1",
"nodemon": "^2.0.12",
"ts-node-dev": "^2.0.0"
},
"bugs": {
"url": "https://github.com/CrispenGari/initialiseur/issues"
},
"homepage": "https://github.com/CrispenGari/initialiseur#readme",
"keywords": [
"node.ts",
"node.js",
"typescript",
"ts",
"nodejs-backend",
"javascript",
"js",
"express",
"backend"
]
}
When i'm testing it locally by running:
npm start
# or
yarn start
Everything is working fine, but after publishing it to npm to start it i run the following command:
npx initialiseur
Then I'm getting the error from a command line. The whole error is as follows:
C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:42536
ts.Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.");
^
Error: Debug Failure. False expression: Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.
at Object.resolveTypeReferenceDirective (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:42536:18)
at C:\Users\crisp\AppData\Roaming\npm\node_modules\ts-node\src\resolver-functions.ts:131:51
at Array.map (<anonymous>)
at Object.resolveTypeReferenceDirectives (C:\Users\crisp\AppData\Roaming\npm\node_modules\ts-node\src\resolver-functions.ts:130:31)
at actualResolveTypeReferenceDirectiveNamesWorker (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:116673:163)
at resolveTypeReferenceDirectiveNamesWorker (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:116973:26)
at processTypeReferenceDirectives (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:118455:31)
at findSourceFileWorker (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:118340:21)
at findSourceFile (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:118195:26)
at processImportedModules (C:\Users\crisp\AppData\Roaming\npm\node_modules\initialiseur\node_modules\typescript\lib\typescript.js:118601:25)
From the above error i can tell that the problem maybe comming from typescript, I'v tried changing version of typescript but still it's not working. In my src/index.ts it looks as follows:
#!/usr/bin/env ts-node
import path from "path";
import inquirer from "inquirer";
import { writeFile, readFile } from "fs/promises";
....
Running npm install -g ts-node#latest fixed it for me. I needed to update my globally installed ts-node version.
To reiterate previous answers for yarn users:
yarn add -D ts-node#latest solved it for me. These are my versions now:
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
The top answer probably shouldn't recommend a downgrade.
Edit
If you continue to face issues, try deleting your node_modules folder and reinstalling by running yarn.
If it still doesn't work, you may need to add these versions to your resolutions field in package.json, and then run yarn install --force.
{
"resolutions": {
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
}
}
However, I consider this a bit of a temporary measure, and I wouldn't recommend leaving the resolutions in forever.
Getting the same as of a couple of days.
Reverting ts-node to v10.6.0 fixes it for me.
It is hapening in typescript 4.7.
I lowered my typescript to 4.6.4, and the error disappeared
Update the Typescript as #alex-totolici has suggested: npm i typescript#latest
And update the ts-node: npm i ts-node#latest
Remeber to distinguish between global ts-node and package ts-node;
You have to use npx to run local ts-node
> npx ts-node ...
Anyway, this is what I finally found after 30 mins of repeatedly rm -rf node_nodules and yarn add ts-node#latest.
These changes in the package.json worked for me.
"ts-node": "~10.7.0"
"typescript": "~4.6.4"
Try updating all you packages including typescript
To update typescript: npm i typescript#latest
Here is a package to check for updates: https://www.npmjs.com/package/npm-check-updates
I had the same issue, and already ran the latest versions of typescript and ts-node.
Updating nodemon npm install -g nodemon#latest solved it for me!
I just figure out that the problem was coming from inquirer import when i commented the import it just worked:
// import inquirer from "inquirer";
I suspect that the inquirer types and my current typescript version are not lining up. So you must as well try to debug by commenting imports if the above answers did not work for you.
I don't know exactly why but the problem comes from a #type package, you can find a line similar to this /// <reference types='node' /> if you delete it won't have this problem anymore
Using ts-node-dev version 2.0.0 fixes this problem.
Note you'll have to manually specify the version as by default this version may not get installed.
Running this solved the issue:
npm install --save-dev ts-node#latest
Try newer version of typescript and ts-node .
i have the same problem but it works fine now with below version:
"ts-node": "~10.7.0",
"typescript": "~4.6.4",
ERROR in Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working
with an outdated resolveTypeReferenceDirectives signature. This is probably not a problem in TS itself.
I still see the issue even after updating the version of Typescript & ts-node with latest versions.

How connect SciChart to Nuxt

I need how coonect SciChart to Nuxt.js
i did
npm init nuxt-app "scichart"
npm install scichart
and i catch error
packeg.json
{
"name": "scichart",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"buildsci": "webpack",
"startsci": "webpack-dev-server"
},
"dependencies": {
"core-js": "^3.15.1",
"nuxt": "^2.15.7",
"scichart": "^2.0.0"
},
"devDependencies": {
"copy-webpack-plugin": "^6.3.2",
"webpack": "^4.46.0 ",
"webpack-cli": "^4.9.0",
"webpack-dev-server": "^4.3.1"
}
}
There are now a number of samples on the SciChart.js Github showing how to setup SciChart in frameworks. These include:
Next.js
Nuxt.js
React
Vue.js
Blazor
Angular
Just Javascript (no framework)
Plus many more. The common problem with these frameworks is loading WebAssembly. SciChart.js uses WebAssembly to achieve really high performance 2D & 3D charts & graphs. Wasm file needs to be in the output folder when your project is built. This is different for every framework.
There is now a page on the SciChart.js Documentation showing how to load webassembly flawlessly without requiring Webpack or Copy plugins in package.json.
See the how-to article here: Creating a new SciChartSurface and loading Wasm
Deploying Wasm (WebAssembly) and Data Files with your app
If you receive an error message when running your app, you may not
have deployed the Wasm (WebAssembly) or data files correctly. Below
are some steps on how to resolve that.
Error: Could not load SciChart WebAssembly module. Check your build
process and ensure that your scichart2d.wasm, scichart2d.data and
scichart2d.js files are from the same version
Option 1: Package Wasm & Data Files with WebPack (or similar)
...
Option 2: Load Wasm from URL with SciChartSurface.configure() or
useWasmFromCDN()
...
We've packaged a helpful function that
automatically loads the latest & correct version of SciChart's Wasm &
Data files from CDN.
To use this, instead of calling
SciChartSurface.configure() passing in a URL, call
SciChartSurface.useWasmFromCDN().
import {SciChartSurface} from "scichart/Charting/Visuals/SciChartSurface";
export async function initSciChart() {
// Call this once before any SciChartSurface is shown.
// This is equivalent to calling SciChartSurface.configure() with the CDN URL (JSDelivr)
SciChartSurface.useWasmFromCDN();
}

"You may need an additional loader to handle the result of these loaders."

I am currently trying to build a State Management Library for ReactJs. But as soon as I implement it into my React project (created with create-react-app), it starts dropping this error:
Failed to compile.
path/to/agile/dist/runtime.js 116:104
Module parse failed: Unexpected token (116:104)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| if (subscriptionContainer instanceof sub_1.CallbackContainer) subscriptionContainer.callback(); // If Component based subscription call the updateMethod which every framework has to define
|
> if (subscriptionContainer instanceof sub_1.ComponentContainer) if (this.agileInstance.integration?.updateMethod) this.agileInstance.integration?.updateMethod(subscriptionContainer.component, Runtime.formatChangedPropKeys(subscriptionContainer));
| }); // Log Job
|
If I comment out the highlighted lines of code mentioned in the error, it jumps to another point and complains there. But it can't be a syntax error because then TypeScript would complain in the IDE, too.
How the tool works:
At the start you have to define a framework, in this case React. Then you can create a State and subscribe this State to a React Functional Component via a Hook.
The Hook used to bind the State to the React Component simply creates a callback which triggers a re-render (via mutating a useReducer) and assigns this callback to the subscribed State.
If you want to know more checkout this repo:
https://github.com/agile-ts/agile
Dependencies:
Third Party State Management library:
"dependencies": {
"#types/chai": "^4.2.12",
"#types/mocha": "^8.0.2",
"chai": "^4.2.0",
"eslint-config-prettier": "^6.11.0",
"mocha": "^8.1.1",
"prettier": "2.0.5",
"ts-node": "^8.10.2",
"tsc-watch": "^4.1.0",
"tslib": "^2.0.0",
"typescript": "^3.9.7"
}
Node: v14.8.0
React Project:
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"#types/jest": "^24.0.0",
"#types/node": "^12.0.0",
"#types/react": "^16.9.0",
"#types/react-dom": "^16.9.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3",
"typescript": "~3.7.2",
"agile-framework": "file:../../"
},
React: 16.13.1
NPM: 6.14.7
The problem is that you're emitting ES2020 to dist/. If you look at the line it's complaining about:
if (subscriptionContainer instanceof sub_1.ComponentContainer) if (this.agileInstance.integration?.updateMethod) this.agileInstance.integration?.updateMethod(subscriptionContainer.component, Runtime.formatChangedPropKeys(subscriptionContainer));
// ^^ // ^^
you can see it's using the optional chaining operator in the emitted code. Consumers of your library will therefore need to have appropriate configuration to handle this kind of code. Your example consumer, the CRA app, is using Babel; although the setup does have the transform for optional chaining, it's only run on the source code for the React app itself, not its dependencies (including your library).
One option for fixing it is to emit less modern code, which will reduce the amount of configuration needed by consumers. For example, if you target ES6 using the following settings in tsconfig.json:
{
"target": "ES6",
"lib": ["DOM", "ES6", "DOM.Iterable", "ScriptHost", "ES2016.Array.Include"],
// ...
}
the React app can at least start without you needing to change your source code.
In case you are not the author of the library, or you don't want to change it as the accepted answer suggests, you can do as follows:
change browserslist as #adlerer suggests:
"browserslist": [
">0.2%",
"not dead",
"not op_mini all"
],
(make sure you don't have special config for development in browserslist)
clear npm cache:
npm cache clean --force
reinstall things like #Gel suggests:
rm -rf node_modules && rm -f package-lock.json && npm i
This is what helped me after hours of research and trials.
Though it's late but still it may help someone.
In my case, I forgot to add the
"jsx": "react"
in my tsconfig.json.
In my case setting more conservative compilation targets in package.json helped to resolve this issue:
"browserslist": [
">0.2%",
"not dead",
"not op_mini all"],
The issue in this case is that the version 3.2.0 of react-leaflet doesn't work for every project (i don't really know why).
im working with react using CRA take note before doing anything
Now the solution...
uninstall react-leaflet
Go to package.json and paste this lines
"react-leaflet": ">=3.1.0 <3.2.0 || ^3.2.1",
"#react-leaflet/core": ">=1.0.0 <1.1.0 || ^1.1.1",
that's the way i solved the problem.
the link to the answer in another website.
https://www.gitmemory.com/issue/PaulLeCam/react-leaflet/891/860223422
In my case I was trying to import dependencies from "react-leaflet" to my old project but then just after importing dependencies I faced the same issue. I solved my problem by these procedures.
In terminal:
rm -rf node_modules && rm -f package-lock.json
npm cache clean --force
I know this may sound irrelevant but in next step I updated these five dependencies in "package.json" to latest versions:
1- "#testing-library/jest-dom"
2- "#testing-library/react"
3- "#testing-library/user-event"
4- "react-scripts"
5- "web-vitals"
I guess the problem is somehow related to two last dependencies but I updated all five of them just in case.
then in terminal:
npm i
sudo npm update -g

How can I publish an NPM module with both commonjs and es6 versions?

I have a module I want to publish to npm. I have found some "solutions" that are 4+ years old, examples using babel 5.x, and other problems that made the examples not work as shown.
Ideally I want to write my code using es6 and build/transpile with babel such that it can be imported with require() in scripts or import in modules.
Right now, here's my (sample) module that shows what I've tried.
// index.js
export default function speak () {
console.log("Hello, World!");
}
// .babelrc
{
"comments":false,
"presets": [
["#babel/env", {"modules": "commonjs"}]
],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
"add-module-exports"
]
}
// package.json
{
"name": "foo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.10.5",
"#babel/core": "^7.10.5",
"#babel/plugin-transform-modules-commonjs": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"babel-plugin-add-module-exports": "^1.0.2"
}
}
And, finally, a demo script (demo.js)
// demo.js
const speak = require('./dist/index.js');
speak();
When I do npm run build and then node demo.js, it works as expected:
Hello, World!
I would also like to be able to have a module (add "type":"module" to package.json) and then use a demo.js file this way:
import speak from './dist/index.js';
speak();
However, I get this an error that a default export isn't available:
import speak from './dist/index.js';
^^^^^
SyntaxError: The requested module './dist/index.js' does not provide an export named 'default'
I don't really care what the answer is, I'd just like to know what the best practices are. Should I just export as ES6? Should I just require commonjs? Is there a way of transpiling with two available targets?
Note:
node v14.5.0
npm v6.14.6
#babel/core v7.10.5
You can use a bundler like webpack or rollup in combination with babel. They provide options to compile to multiple targets. Normally any library code is compiled to below targets:
ESM or MJS (Ecmascript modules)
UMD (Universal Modules)
You can also compile to CJS (CommonJS module) or IIFE (Immediately invoked function expression).
UMD and ESM are pretty much standard these days (esp. UMD because it is combination of IIFE, CJS and AMD).
You can explore official documentation for Webpack or Rollup. However, I have created a tool which you can use to achieve the output you are looking for. https://www.npmjs.com/package/rollup-boilerplate
You can check it out, play around with it, hack it. I think it can be good starting point. You can checkout this article to get started: https://medium.com/#contactsachinsingh/setting-up-a-rollup-project-under-two-minutes-fc838be02d0e

index.js for npm package for browser transpiled with babel

Having some problems figuring out how to completely create and setup an npm package that I want to publish for use in browser environments.
I believe I'm missing some info on how to generate the index file.
I have the testpackage linked into my test application via npm link in both project directories. My test application is setup with webpack and babel and is written in es6, so using import and export.
The source is written in es6 and being transpiled via babel. Here's the relevant section of the package.json with the build command:
{
"name": "testpackage",
"main": "index.js",
"scripts": {
"build": "babel src --out-dir dist",
"lint": "eslint ."
},
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"
}
}
I've tried creating the index.js file in two ways, first via es6 and again as module.exports but neither is working.
// es6 index.js in testpackage
import store from './dist/store';
import attach from './dist/attach';
export {store, attach};
--
// index.js with modules.exports
const path = require('path');
module.exports = {
store: require(path.resolve(__dirname, './dist/store')),
attach: require(path.resolve(__dirname, './dist/attach'))
}
In this es6 first case, the test application that I'm importing testpackage into isn't finding dist.
Module not found: Error: Can't resolve 'dist/store' in '/usr/local/apps/testpackage'
In the second case, the code is clearly meant to run via node, but instead is just being loaded directly into the browser. I was thinking the webpack + babel transpiling step in the test app should run this, but its not.
What about this setup am I missing?
Finally figured this out. The first approach was right. I needed to create an es6 index.js in the src directory that imports and exports the other files. Then babel transpiles this into the /dist directory, and main in package.json is pointed to /dist/index. The problem was that I didn't have the index being transpiled.

Categories