rollup plugin "#rollup/plugin-commonjs" parsing package.json and throwing unexpected token error - node.js

TL;DR: Why is #rollup/plugin-commonjs looking in my package.json and how can I stop that so that I don't have to include #rollup/plugin-json arbitrarily to fix the problem?
I have a file written in JS for Node.js, CommonJS require() / module.exports() that I want to work in the Browser, so I am using Rollup to bundle and 'browserify' the Node.js code.
Environment
macOS Monterey Version 12.4
npm version 8.3.1
node version 16.14.0
rollup version 2.75.6
#rollup/plugin-json version 4.1.0
rollup.config.js
Here is my rollup.config.js:
// rollup.config.js
import commonjs from '#rollup/plugin-commonjs';
// import json from '#rollup/plugin-json';
const devMode = (process.env.NODE_ENV === 'development');
console.log(`${ devMode ? 'development' : 'production' } mode bundle`);
export default [
{
input: "test/_client_test.js",
output: {
file: 'build/test/test.js',
format: 'iife'
},
plugins: [
commonjs()
]
}
];
Problem
When running npm rollup -c I get the following output:
[!] (plugin commonjs--resolver) Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
package.json (2:8)
1: {
2: "name": "my-package",
^
3: "version": "0.0.1",
4: "description": "hello world",
Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
at error (/***/node_modules/rollup/dist/shared/rollup.js:198:30)
at Module.error (/***/node_modules/rollup/dist/shared/rollup.js:12553:16)
at Module.tryParse (/***/node_modules/rollup/dist/shared/rollup.js:12930:25)
at Module.setSource (/***/node_modules/rollup/dist/shared/rollup.js:12835:24)
at ModuleLoader.addModuleSource (/***********/rollup.js:22309:20)

Related

Cannot find module 'node:url' when executing typescript from webstorm

I have written this small typescript hello world example
import axios from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
client.get('https://example.com');
when I run this from webstorm i get the following error
/usr/bin/node /usr/local/lib/node_modules/ts-node/dist/bin.js /home/nayana/WebstormProjects/hello-world/hello.ts
Error: Cannot find module 'node:url'
anyone have idea on how to resolve this?
I already tried npm install node:url and url
i have isolated the error to this line
const client = wrapper(axios.create({ jar }));
The issue maybe is related to the node version.
The axios-cookiejar-support requires a specific node version ("node": ">=14.18.0 <15.0.0 || >=16.0.0").
Check node --version and package-lock.json.
Sample:
"node_modules/axios-cookiejar-support": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/axios-cookiejar-support/-/axios-cookiejar-support-4.0.3.tgz",
"integrity": "sha512-fMQc0mPR1CikWZEwVC6Av+sD4cJuV2eo06HFA+DfhY54uRcO43ILGxaq7YAMTiM0V0SdJCV4NhE1bOsQYlfSkg==",
"dependencies": {
"http-cookie-agent": "^4.0.2"
},
"engines": {
"node": ">=14.18.0 <15.0.0 || >=16.0.0"
},
"peerDependencies": {
"axios": ">=0.20.0",
"tough-cookie": ">=4.0.0"
}
},
You might need to install a later version of node.js.
I was running 14.17.6 and after installing 16.17.0 with nvm then I was able to run the project.
If you have nvm installed you can install a specific version of node e.g.
nvm install 16.17.0
make sure the types array in your tsconfig.json file contains "node"
{
"compilerOptions": {
"types": [
// ... your other types
"node"
],
// ... your other settings
},
}
The only thing you need to do, if you didn't install typescript is to change in the vite.config.js file, the import line like this:
import { fileURLToPath, URL } from 'node:url'
To:
import { fileURLToPath, URL } from 'url'

setup webpack config in nextJS (next.config.js)

I'm working with NextJS and using react-data-export plugin to generate xls files.
in the description it says :
This library uses file-saver and xlsx and using
json-loader will do the magic for you.
///webpack.config.js
vendor: [
.....
'xlsx',
'file-saver'
],
.....
node: {fs: 'empty'},
externals: [
{'./cptable': 'var cptable'},
{'./jszip': 'jszip'}
]
but I have no idea how to implement it and got error like this :
The static directory has been deprecated in favor of the public directory. https://err.sh/vercel/next.js/static-dir-deprecated
Defining routes from exportPathMap
event - compiled successfully
> Ready on http://localhost:80 or http://localhost
> Ready on https://localhost:443 or https://localhost
event - build page: /menu_accounting/ReportGross
wait - compiling...
error - ./node_modules/react-export-excel/node_modules/xlsx/xlsx.js
Module not found: Can't resolve 'fs' in '/home/ahmadb/repos/lorry-erp/node_modules/react-export-excel/node_modules/xlsx'
Could not find files for /menu_accounting/ReportGross in .next/build-manifest.json
I had the same problem, the solution for me was this:
Install this packages (if you installed, ignored this)
npm install file-saver --save
npm install xlsx
npm install --save-dev json-loader
Add this to your nextjs.config.js
const path = require('path')
module.exports = {
...
//Add this lines
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
}

Runing nodegit in Electron fails

I installed nodegit 0.26.5 via npm and import the package in the renderer part of my Electron application. During compilation I receive this error below:
WARNING in ./node_modules/nodegit/dist/nodegit.js
Module not found: Error: Can't resolve '../build/Release/nodegit.node' in '/Users/steve/Documents/git/git_reader/node_modules/nodegit/dist'
ERROR in ./node_modules/nodegit/dist/nodegit.js
Module not found: Error: Can't resolve '../build/Debug/nodegit.node' in '/Users/steve/Documents/git/git_reader/node_modules/nodegit/dist'
ERROR in ./node_modules/nodegit/dist/nodegit.js
Module not found: Error: Can't resolve '../package' in '/Users/steve/Documents/git/git_reader/node_modules/nodegit/dist'
In my node_modules/nodegit/build directory, I only have a Release directory. Does anyone have an idea what I miss here?
I created a repo, which I forked from a boilerplate template. I only added nodegit and #types/nodegit as a dependency and imported it in details.component.ts
https://github.com/Githubber2021/electron-nodegit-error
git clone https://github.com/Githubber2021/electron-nodegit-error.git
npm install
npm run electron:local
to reproduce the issue. Can anyone reproduce the error on their machine? What am I missing here? Thank you so much for any help or hint!!
I'm using nodegit 0.27 and the error message for me was slightly different, it was
nodegit.js:1088 Uncaught Error: Cannot find module '../package'
Note that I'm using webpack together with electron forge and in my package.json I have the following. (I replaced the irrelevant parts with ...)
{
"name": ...
"version": ...
"description": ...
"config": {
"forge": {
"packagerConfig": {},
"makers": [
...
],
"plugins": [
[
"#electron-forge/plugin-webpack",
{
"mainConfig": ...
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
...
]
}
}
]
]
}
},
...
}
And in my webpack.renderer.config.js I needed to add an externals field to my exports so that they look something like this
module.exports = {
...
externals: {
nodegit: 'commonjs nodegit'
},
};
Then in my main.ts, the main process I have
(global as any).mynodegit = require('nodegit');
And then I use IPC to access nodegit within my renderer process. Note that the #ts-ignore is required to suppress error messages from typescript.
import { remote } from "electron";
// #ts-ignore
import * as Git from "#types/nodegit";
// #ts-ignore
const Git = remote.getGlobal('mynodegit');
Here is the boilerplate that helped me with this https://github.com/newblord/electron-react-webpack-nodegit-boilerplate

Cannot test jest with monaco editor - unexpected token

Running jest on the application fails with:
Details:
/home/**/node_modules/monaco-editor/esm/vs/editor/editor.api.js:5
import { EDITOR_DEFAULTS } from './common/config/editorOptions.js';
^
SyntaxError: Unexpected token {
> 1 | import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
| ^
2 |
3 | /**
4 | * Get create function for the editor.
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (src/utils/editor-actions.js:1:1)
Application has installed packages for jest and babel-jest.
Babel config:
const presets = [
[
"#babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1"
},
useBuiltIns: "usage",
corejs: 3,
}
],
"#babel/preset-react"
];
const plugins = [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties",
"babel-plugin-styled-components"
];
module.exports = { presets, plugins };
The import statement as suggested in the docs for lazy loading modules from monaco leads to the esm folder, which jest is not familiar with.
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
By default, babel-jest would not transform node_modules and hence anything referencing the monaco-editor would error out. A possible solution is to include monaco-editor package into the compilation step by transformIgnorePatterns as mentioned in the docs
Add these to the jest config:
{
"transformIgnorePatterns": [
"node_modules\/(?!(monaco-editor)\/)"
]
}
PS: If you are using jest-dom, it might start complaining on not implmenting certain features from monaco-editor, you can mock it out with:
jest.mock("monaco-editor/esm/vs/editor/editor.api.js");
The only workaround that helped me in that issue (from here):
In folder __mocks__ create file react-monaco-editor.js with content:
import * as React from 'react';
export default function MonacoEditor() {
return <div />;
}
I have the same issue with Jest and Monaco and to make the tests pass I had to:
Add a moduleNameMapper for monaco-editor: #133 (comment)
Configure a setupTests.js like explained here: stackOverflow
I'm using:
"jest": "^24.9.0"
"babel-jest": "24.9",
"monaco-editor": "^0.20.0"
"react-monaco-editor": "0.33.0",
"monaco-editor-webpack-plugin": "^1.8.2",

Dynamically import webpack in Node.js

I´m trying to dynamically import webpack in Node.js
if (condition) {
import('webpack').then(webpack => webpack);
}
However in my terminal I see the following error:
C:\Users\myUser\react\node_modules\#babel\core\lib\transformation\normalize-file.js:209
throw err;
^
SyntaxError: C:\Users\myUser\react\server\index.js: Support for the experimental syntax 'dynamicImport' isn't currently enabled (23:3):
19 |
20 | if (condition) {
> 21 | import('webpack').then(webpack => webpack);
| ^
22 |
Add #babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.
I have #babel/plugin-syntax-dynamic-import installed and in my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties"
]
}
I even tried to add it to the webpack conf file under the rule for .js with loader "babel-loader".
I´m trying to avoid CmJS
const webpack = require('webpack');
In any case I receive the same error and I cannot find a solution. Did anyone go through this? Thanks
add plugins: ["dynamic-import-webpack"] to .babelrc
and also install plug $npm i babel-plugin-dynamic-import-webpack --D

Resources