#babel/register support source maps on runtime - node.js

There is code that is transpiled by babel. But on runtime error it shows a wrong line number.
I run the script this way.
node -r ./runner.js ./index.js
It uses the runner.
console.log('Runner. Registers babel.')
require('source-map-support').install()
require('#babel/register')({
extensions: ['.js'],
ignore: [
/node_modules[\\/](?!console-command-manager)/
],
});
Babel register uses the config from babel.config.js
console.log('Babel. Configuration.');
module.exports = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }]],
plugins: [],
sourceMap: "inline"
};
When I throw an error in the code on runtime. It shows me wrong line numbers. I understand that source-map-support does not work.
VSCode debugging goes well. The editor see and understand source maps.
Help me to make source-maps workable.

The plugin registration of babel-plugin-source-map-support in babel.config.js is missed.
Read the description of the library babel-plugin-source-map-support
There two libraries are needed: babel-plugin-source-map-support and source-map-support. Install them both.
In babel file, register source-map-support plugin
{
sourceMaps: true,
plugins: ['source-map-support', ...]
}
Enable on runtime in a file at the top.
require('source-map-support').install()
Now, when it fails it has to show the right error line number of the source code.

Related

Jest resolver cannot find a file which path ressembles existing node modules

I have upgraded jest from version 27 to version 29.
Since then, some indirect file resolve do not work anymore.
Here is my config:
module.exports = {
roots: ['app/javascript/__tests__/'],
testMatch: ['**/?(*.)(spec|test).js?(x)'],
testEnvironment: 'jsdom',
testRunner: 'jest-jasmine2',
moduleDirectories: [
'node_modules',
'app/javascript',
'app/javascript/__tests__'
],
transform: {
'^.+\\.jsx?$': 'babel-jest'
},
moduleNameMapper: {
'^.+\\.(svg)$': '<rootDir>/app/javascript/__tests__/fileMock.js'
},
setupFiles: ['./app/javascript/__tests__/setup.jsx']
}
There is a file in my code base, let's say app/javascript/MyReactComponent.jsx, which is imported as part of my tested component, and that contains the following import line:
// app/javascript/MyReactComponent.jsx
import 'firebase/init'
Expected behavior
Until today, I could run jest, and it was finding all my code as expected, inclluding the above import, which is located here:
app/javascript/firebase/init.js
Error
Instead, running jest throws the following error.
Cannot find module 'firebase/init' from 'app/javascript/MyReactComponent.jsx'
FWIW, I have traced the resolver code up to the default jest resolver, and it seems like it tries to get the file from within the firebase node module, instead of fetching the init.js file in the firebase directory.
Question
Is there a way to adjust my configuration in order for the resolver to find my file?
Have you tried adding an entry for that aliased module in moduleNameMapper?
moduleNameMapper: {
'^.+\\.(svg)$': '<rootDir>/app/javascript/__tests__/fileMock.js',
'^firebase/init': '<rootDir>/app/javascript/firebase/init.js'
}

How to bundle node module CSS into a vscode extension

My Visual Studio Code extension uses the node module highlight.js which comes with a folder full of CSS files. These provide colour schemes for syntax colouring. It has become necessary to bundle some of the CSS files.
It's about bundling an asset
The objective is to bundle a CSS file and at run-time access the file content as a string. If that can be achieved without an import statement that would be perfect. Normally, how exactly one accesses the content of the bundled file would be a separate question, but I have a feeling that content retrieval and how one should go about bundling the asset are closely entwined.
I freely admit to having a weak understanding of WebPack.
The story so far
The bundler is specified in package.json as "webpack": "^5.4.0" but I don't know how to ascertain what is actually present. It is conceivable that there is something wrong with my setup: when I try to run webpack --version on a command prompt in the project folder, it responds
CLI for webpack must be installed.
webpack-cli (https://github.com/webpack/webpack-cli)
We will use "npm" to install the CLI via "npm install -D webpack-cli".
Do you want to install 'webpack-cli' (yes/no):
The first time this happened I responded yes. After a flurry of installation and another try the same thing happened. However, vsce package has no trouble using webpack for a production build and pressing F5 to debug successfully puts together a development build in a dist folder with an unminified file I can examine (which is how I know the file mentioned below is being bundled).
Moving on from there I've modified webpack.config.js like so
//#ts-check
'use strict';
const path = require('path');
/**#type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context -> https://webpack.js.org/configuration/node/
entry: './src/extension.ts', // the entry point of this extension, -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]'
},
devtool: 'source-map',
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, -> https://webpack.js.org/configuration/externals/
},
resolve: {
// support reading TypeScript and JavaScript files, -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js', '.css']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
};
module.exports = config;
As you can see there are rules and loaders for CSS.
When I add this import
import "../node_modules/highlight.js/styles/atelier-dune-light.css";
webpack happily builds the bundle and when I inspect it I can find the bundled CSS.
However, when I try to load the extension in the extension debug host, it fails to load, with this message.
Activating extension 'pdconsec.vscode-print' failed: document is not defined.
Enabling break on caught exceptions reveals this rather surprising exception.
Exception has occurred: Error: Cannot find module 'supports-color'
Require stack:
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\node_modules\debug\src\node.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\node_modules\debug\src\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\get-uri\dist\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\vscode-proxy-agent\out\agent.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar\vscode-proxy-agent\out\index.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-amd.js
- c:\Users\Peter\AppData\Local\Programs\Microsoft VS Code\resources\app\out\bootstrap-fork.js
OK, so activation failed because the loader barfed. But WTF does importing CSS have to do with support-color?
Remove the import and it runs just fine. I really don't know how to respond to this; it's not clear to me why a demand for a stylesheet should cause that error. At this point I look to others for guidance and advice.
Remove style-loader from webpack.config.js to fix the error.
Pull the CSS as a string like this. Note the abbreviated path.
const cssPath: string = "highlight.js/styles/atelier-dune-light.css";
const theCss: string = require(cssPath).default.toString();
You do not need the import statement, the use of require will cause Webpack to bundle the files, but you still have to remove style-loader to avoid the loader error.

Jest not working with fs/promises typescript

I'm trying to add jest to my typescript project for testing, but when I run jest, it keeps giving me the error
● Test suite failed to run
Cannot find module 'fs/promises' from 'src/path/to/file'
Require stack:
src/path/to/file
test/test.ts
> 3 | import fsp from 'fs/promises';
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
at Object.<anonymous> (src/path/to/file.ts:3:1)
The program itself runs fine, but whenever I try to run jest on it, it runs into this issue. I've tried adding jest.mock('fs');, which didn't help, and adding jest.mock('fs/promises'); gives the same error in the test file.
I've read that certain versions of Node don't support 'fs/promises' and instead need require('fs').promises, which I've tried and still doesn't work (I'm on Node version 12).
How can I configure jest to be able to load 'fs/promises'? I've included my jest.config.js file below:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: [
'/node_modules/',
'/out/',
],
moduleDirectories: [
'.',
'node_modules'
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx'
]
}
Turns out Jest is interpreting 'fs/promises' as a folder in the file system, which is incorrect as this is an API from the fs module. To fix this, simply add
moduleNameMapper: {
"fs/promises": "<rootDir>/node_modules/fs-extra/lib/fs"
}
to jest.config.js to tell Jest to map the module 'fs/promises' to the file <rootDir>/node_modules/fs-extra/lib/fs, or wherever the fs module is defined in your file system.

Error in ./node_modules/node-libcurl/lib/binding/node_libcurl.node

I'm a C++ developer and beginner in the Node world.
I would like to create a CEP and VUE based Photoshop plugin.
The skeleton plugin works well.
I would like to use node-libcurl package for this plugin.
I installed libcurl - It's OK.
npm i node-libcurl --save
I put down into my C4.js
const { curly } = require('node-libcurl');
When I want to build my project I got this error:
INFO Starting development server... 98% after emitting CopyPlugin
ERROR Failed to compile with 1 error
7:26:51 PM error in
./node_modules/node-libcurl/lib/binding/node_libcurl.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are
configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for > > this binary file)
# ./node_modules/node-libcurl/dist/Easy.js 5:17-60
# ./node_modules/node-libcurl/dist/index.js
# ./src/c4/C4.js
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.1.22:8080&sockPath=/sockjs-node
(webpack)/hot/dev-server.js ./src/main.js
I tried this webpack.config.js in .... \node_modules\node-libcurl
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
... but it did not work.
I appreciate any help
Thx:
Carlos
It was my fail.
I got answer from developer.
This library is not supposed to work in the Browser, it is a backend-only library.
/Carlos

Error while loading config - You appear to be using a native ECMAScript module configuration file (Jest)

UPDATED.
This error is coming up when I am making a pull request. There is a github workflow audit that runs checks on the pull request and it loads the test file from another repository.
- name: Run Audits
run: npx jest audits/ch-2 --json --outputFile=audits/ch-2.json --noStackTrace
Test suite failed to run
/Users/frankukachukwu/StudioProjects/covid-19-estimator-tksilicon-js/babel.config.js: Error while loading config - You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
How do I solve this issue?
SOLVED: For anyone who encounters this problem. This has got to do with Babel settings. The use of .mjs, cjs or js extension for the babel.config.extension. In my case where I was running LTE Node 12.6.2. I needed this configuration at the root of my directory babel.config.cjs. cjs is what is applicable for Nodejs when using "type"="module". See more about it here on babel docs.
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current'
}
}
]
]
};
And jest.config.cjs at the root too.
In addition to "cjs" solution, I was able to resolve this issue by converting babel.config.js to babel.config.json:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
],
"#babel/preset-typescript"
]
}

Resources