ParseError: /node_modules/preact/compat/dist/compat.module.js/jsx-runtime.js - reactjs

Error:
ParseError: /node_modules/preact/compat/dist/compat.module.js/jsx-runtime.js
Error: ENOTDIR: not a directory, open 'node_modules/preact/compat/dist/compat.module.js/jsx-runtime.js'
Issue: When I tried to migrate my react app from react-bootstrap v1 to react-bootstrap v2, I am getting the above error.
root cause: I guess the reason could be because of the aliasing method I use in the rollup.config.js file below. My objective in the below code is to alias react to preact which is working fine till react-bootstrap 1.6.4 but the error arises when I try to update/migrate the existing react-bootstrap 1.6.4 to it's latest version 2.2.3
Code:
`` alias({
entries: [
...['react', 'react-dom'].map(find => (
{ find, replacement: path.resolve(__dirname,'./node_modules/preact/compat/dist/compat.module.js') }
))
]
}), ``
Workaround: tried many workarounds for aliasing react to preact(rollup, webpack etc., from the official documentation provided in preact, but nothing seems to be working. The current preact version I am using is 10.x
My query: Is there a way to resolve this issue? I didn't make any code changes during the migration but the existing rollup config aliasing is breaking. Thanks in advance

You're aliasing incorrectly. The newer version of react-boostrap must use the new(-er) JSX runtime, and your alias is creating a junk path.
Take the following:
import { jsx } from 'react/jsx-runtime';
Your alias sees "react", and converts it to your alias:
import { jsx } from './node_modules/preact/compat/dist/compat.module.js/jsx-runtime';
Which is clearly not right.
You want to use the alias listed on our docs site:
import alias from '#rollup/plugin-alias';
module.exports = {
plugins: [
alias({
entries: [
{ find: 'react', replacement: 'preact/compat' },
{ find: 'react-dom/test-utils', replacement: 'preact/test-utils' },
{ find: 'react-dom', replacement: 'preact/compat' },
{ find: 'react/jsx-runtime', replacement: 'preact/jsx-runtime' }
]
})
]
};

Related

three.js three-nodes showing 'Module not found' error

./node_modules/three/examples/jsm/renderers/webgpu/nodes/WebGPUNodeBuilder.js
Module not found: Can't resolve 'three-nodes/core/CodeNode.js'.
I am using react, import three from node_modules, It throws an error like this.
What can I do to solve it?
Why "three-nodes/": "./jsm/nodes/" ?
I think this GitHub Issue is relevant:
https://github.com/mrdoob/three.js/issues/24377
three-nodes is an alias of three/examples/jsm/nodes, therefore, if you have this issue you need to make your program recognize this alias. You can find way to do it in Vite from this reply, or in rollup from the following config (with support of #rollup/plugin-alias)
{
...,
plugins: [
...,
alias({
entries: [
{ find: 'three-nodes', replacement: 'three/examples/jsm/nodes' }
]
})
]
}

Vitejs | Uncaught Error: Dynamic require of "<path>.svg" is not supported

I'm trying to use react-flagpack in my project that uses Vite, but whenever I use it i get the following error:
Uncaught Error: Dynamic require of "node_modules/flagpack-core/dist/flags/cDBuMQWP.svg" is not supported
Is this an issue with Vite? or am I doing something wrong.
Thanks in advance!
As of June 14th 2021 it's now supported. :3
Can you check if this works? I don't know if it will for react-flagpack; this is likely a require statement that is breaking the build... I found a solution using #originjs/vite-plugin-commonjs, which I posted here.
First install the package:
yarn add #originjs/vite-plugin-commonjs -D
or
npm i #originjs/vite-plugin-commonjs -D
And then, in your vite.config file:
import { defineConfig } from 'vite';
import { viteCommonjs, esbuildCommonjs } from '#originjs/vite-plugin-commonjs';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
viteCommonjs(),
],
optimizeDeps: {
esbuildOptions: {
plugins: [
// Solves:
// https://github.com/vitejs/vite/issues/5308
esbuildCommonjs(['react-flagpack'])
],
},
},
});
Then, try loading your file normally. This worked for me using tiny-react-slider which was using a require statement for a .css file

React with TypeScript using tsyringe for dependency injection

I am currently having trouble with my React TypeScript project.
I created my project with npx create-react-app my-app --template typescript.
I recently added tsyringe for dependency injection and was trying to implement it for an apiService. After following the readme(https://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection) for adding primitive values I have hit a block. I already add experimentalDecorators and emitDecoratorMetadata to my tsconfig.json file with no success.
The error actual error I am encountering is:
./src/ts/utils/NetworkService.ts 9:14
Module parse failed: Unexpected character '#' (9:14)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
| let NetworkService = (_dec = singleton(), _dec(_class = (_temp = class NetworkService {
> constructor(#inject('SpecialString')
| value) {
| this.str = void 0;
I am fairly sure this problem is caused by Babel, however I created this with npm create react-app --template typescript and do not seem to have access to the Babel configuration.
NetworkService.ts
#singleton()
export default class NetworkService
{
private str: string;
constructor(#inject('SpecialString') value: string) {
this.str = value;
}
}
Invocation method
bob()
{
const inst = container.resolve(NetworkService);
}
Registering Class in index.ts
container.register('SpecialString', {useValue: 'https://myme.test'});
#registry([
{ token: NetworkService, useClass: NetworkService },
])
class RegisterService{}
React-Scripts manages many of the configs related to the project. For many cases, this is fine and actually a nice feature. However, because React-Scripts uses Babel for it's development environment and does not expose the config.
You have to run npm run eject to expose the configurations.
Please note, this is a one-way operation and can not be undone.
Personally, I prefer more control with my configuration.
After this you can edit the webpack.config.js in the newly created config folder.
Find the section related to the babel-loader in the dev-environment and add 'babel-plugin-transform-typescript-metadata' to the plugins array.
Expanding on Jordan Schnur's reply, here are some more pitfalls I encountered when adding TSyringe to my CRA app:
Use import type with #inject
If you get this error "TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled." replace import with import type for the offending imports. You will encounter this when working with #inject
E.g. replace import { IConfig } from "iconfig" with import type { IConfig } from "iconfig"
Fixing Jest
Your Jest tests will also break with TSyringe, especially when using #inject. I got the error "Jest encountered an unexpected token" with details constructor(#((0, _tsyringe.inject)("")) ("#" marked as the offending token). I took the following steps to fix that in CRA:
Add the line import "reflect-metadata"; to the top of the file src/setupTests.ts
In config/jest/babelTransform.js replace line 18 and following:
From
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});
to:
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
require.resolve('babel-plugin-transform-typescript-metadata')
],
babelrc: false,
configFile: false,
});
Instead of eject, you may use a lib that "overrides" some of your params.
I used craco : https://www.npmjs.com/package/#craco/craco
I've created an simpler DI library that doesn't need decorators or polyfill. Works with CRA like a charm and has cool React bindings
iti
import { useContainer } from "./_containers/main-app"
function Profile() {
const [auth, authErr] = useContainer().auth
if (authErr) return <div>failed to load</div>
if (!auth) return <div>loading...</div>
return <div>hello {auth.profile.name}!</div>
}

TypeScript constructor parameter with modifiers doesn't emit correctly with ts-loader

I was starting to work with a web application built with TypeScript/React/Storybook. I noticed when I write a class:
class MyClass {
constructor(public a) { }
}
console.log(MyClass);
and run the unit tests with jest, or using tsc to emit code, it generates the expected JS code like:
function MyClass(a) {
this.a = a;
}
But when I run it in a Storybook app with development server, it prints out the JS code like:
function MyClass(a) {
_classCallCheck(this, MyClass);
}
I'm thinking if it's related to the TypeScript compiler version picked by ts-loader, but cannot figure it out. I checked the TypeScript version installed to my node_modules folder, and it's v4.1.2, which looks nothing wrong with me.
Also I mentioned Playbook here (and left "playbook" in the tags) only because my app is with it. It might not be directly related to this issue.
Seems like an issue with recent versions #babel/preset-typescript if you are using it. You can change your babel configuration to use "#babel/plugin-transform-typescript" plugin instead of #babel/preset-typescript preset.
More info: https://www.gitmemory.com/issue/babel/babel/8752/486541662
If generated by storybook, your babel config probably looks like:
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-typescript",
],
};
Then change it to:
module.exports = {
presets: [["#babel/preset-env", { targets: { node: "current" } }]],
plugins: ["#babel/plugin-transform-typescript"],
};

Babel Standalone Invalid plugin #babel/plugin-proposal-decorators

I am trying to use babel standalone inside a react app to transpile Angular TypeScript.
The short version:
How can I use #babel/plugin-proposal-decorators and #babel/plugin-proposal-class-properties with babel standalone?
The long version:
This tutorial https://medium.com/#hubert.zub/using-babel-7-and-preset-typescript-to-compile-angular-6-app-448eb1880f2c says that "apparently #babel/plugin-syntax-decorators doesn’t do the work and causes transform errors.". He recommends using the following config in a babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-typescript"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true,
}
],
"#babel/plugin-proposal-class-properties"
]
}
using syntax-decorators does "work" for me but then I get another error that it does not recognise a selector for an imported component.
Since I am using babel standalone I need to use Babel.transform like this:
const TS_OPTIONS = {
presets: [
'typescript',
['es2017', { 'modules': false }],
],
plugins: [
// the following two options "work" but with another error
// 'syntax-decorators',
// 'syntax-class-properties',
// none of these options work
["#babel/plugin-proposal-decorators"],
["#babel/plugin-proposal-class-properties"],
//['plugin-proposal-decorators', { 'legacy': true }],
//['plugin-proposal-class-properties', { 'loose': true }],
// 'plugin-proposal-decorators',
// 'plugin-proposal-class-properties',
// ['syntax-decorators', { 'legacy': true }],
'transform-es2015-modules-commonjs',
],
};
my transpile function (greatly simplified):
export default function transpile(myCode) {
const { code } = Babel.transform(myCode, TS_OPTIONS);
return myCode;
}
No matter how I write the plugins it does not work. I keep getting an error along the lines of
Error: Invalid plugin specified in Babel options: "proposal-decorators"
using the syntax-decorators plugin will transpile the code but I get the following error when importing a component and trying to use the components selector:
Uncaught Error: Template parse errors:
'search-bar' is not a known element:
1. If 'search-bar' is an Angular component, then verify that it is part of this module.
2. If 'search-bar' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
I solved this by upgrading the version of Babel I was using which gave me access to more available plugins. I posted another question that I thought was a different issue but it turns out they were related. I will reference that question here if anyone is interested: Angular Uncaught Error: Template parse errors: is not a known element
with babel-standalone .babelrc wont work .you might need to use transform to apply plugins .i am wondering why you exactly need to use standalone babel ?. if its react or angular you can just use babel only and don't need to use transform

Resources