WebPack React - Support for the experimental syntax 'jsx' isn't currently enabled - reactjs

I've checked every other question and none seem to provide an answer that work for me.
Getting this error when attempting to compile:
27 |
28 | return (
> 29 | <G x={logoPosition} y={logoPosition}>
| ^
30 | <Defs>
31 | <ClipPath id='clip-logo-background'>
32 | <Rect
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
This is the code that is causing it:
import * as React from "react";
import WalletConnectProvider from "#walletconnect/react-native-dapp";
import AsyncStorage from "#react-native-async-storage/async-storage";
export default function WalletConnector() {
return (
<WalletConnectProvider
bridge="https://bridge.walletconnect.org"
clientMeta={{
description: "Connect with WalletConnect",
url: "https://walletconnect.org",
icons: ["https://walletconnect.org/walletconnect-logo.png"],
name: "WalletConnect",
}}
redirectUrl={window.location.origin}
storageOptions={{
asyncStorage: AsyncStorage as any,
}}
>
<>{/* awesome app here */}</>
</WalletConnectProvider>
);
}
This is the package causing it: "#walletconnect/react-native-dapp": "^1.4.1"
I've added .babelrc with the following and problem persists.
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
I've also added babel.confis.json which didn't help and added a babel section in my package.json with the proper plugins/presets and still no change.

For bare CLI project update below files.
Reference: https://github.com/WalletConnect/walletconnect-monorepo/issues/753
Update metro-config.js
module.exports = {
resolver: {
extraNodeModules: require("node-libs-react-native")
},
. . .
};
Add following statement in index.js
require("node-libs-react-native/globals.js");

Related

Trying to implement absolute paths for imports in React Native project using # as alias for ./src/, but get an error in Metro

I am trying to use the # (at) symbol to differentiate the projects own imports from the ones in node_modules.
./src/ contents
So I'd like my imports to be imported as
#components/FlatListMenuItem
#interfaces/appInterface
#screens/HomeScreen
#theme/appTheme
But I'm getting this error in Metro:
error: Error: Unable to resolve module #theme/appTheme from C:\Coding\Capacitacion\React_Native\RNComponents\src\screens\HomeScreen.tsx: #theme/appTheme could not be found within the project or in these directories:
node_modules
7 | import { MenuItem } from "#interfaces/appInterfaces";
8 |
> 9 | import { styles } from "#theme/appTheme";
| ^
10 |
at ModuleResolver.resolveDependency (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:178:15)
at DependencyGraph.resolveDependency (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\node-haste\DependencyGraph.js:264:43)
at Object.resolve (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\lib\transformHelpers.js:170:21)
at resolveDependencies (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\graphOperations.js:466:33)
at processModule (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\graphOperations.js:232:31)
at async traverseDependenciesForSingleFile (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\graphOperations.js:221:3)
at async traverseDependencies (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\graphOperations.js:147:7)
at async DeltaCalculator._getChangedDependencies (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\DeltaCalculator.js:263:42)
at async DeltaCalculator.getDelta (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler\DeltaCalculator.js:90:16)
at async DeltaBundler.getDelta (C:\Coding\Capacitacion\React_Native\RNComponents\node_modules\metro\src\DeltaBundler.js:74:12)
I believe I have it properly configured in tsconfig.json because when I hover over the import directory with the alias in effect, the popup that shows the evaluated path is correct. So the problem must be with the babel.config.js.
What's odd is that it's throwing an error on the themes import on line 9 but all seems good with the import on line 7.
I've looked throught a lot of tutorials on this, and I can't understand what's missing. I'm quite aware that I might be overlooking something extremely evident...
I'm using babel-plugin-module-resolver to handle the aliases for the build.
This is my tsconfig.json:
// prettier-ignore
{
"extends": "#tsconfig/react-native/tsconfig.json", /* Recommended React Native TSConfig base */
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"baseUrl": ".", /* Base directory to resolve non-absolute module names. */
"paths" : {
"#*": ["src/*"]
},
/* Completeness */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
And this is my babel.config.js:
module.exports = {
presets: ["module:metro-react-native-babel-preset"],
plugins: [
[
"module-resolver",
{
alias: {
"#": "./src/",
},
},
],
],
};
And this is the component where I'm using the import statements:
import { FlatListMenuItem } from "#components/FlatListMenuItem";
import { MenuItem } from "#interfaces/appInterfaces";
import { styles } from "#theme/appTheme";

Jest encountered an unexpected token + react markdown

I'm getting an error when trying to run my test file (I'm using react typescript)
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
export {uriTransformer} from './lib/uri-transformer.js'
^^^^^^
SyntaxError: Unexpected token 'export'
5 | const Markdown = ({ text, classStyle }: ITextMedia) => (
6 | <div className={`${classes.mediaParagraph} ${classStyle ?? ''}`}>
> 7 | <ReactMarkdown>{text}</ReactMarkdown>
| ^
8 | </div>
9 | );
10 | export default Markdown;
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (components/media/markdown/index.tsx:7:45)
I already tried adding the React markdown to the transform ignore patterns, but it still doesn't work
here's my jest.config
{
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'next/router': '<rootDir>/__mocks__/next/router.js',
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
},
transformIgnorePatterns: [
'node_modules/(?!react-markdown/)'
]
}
my babel config:
{
"presets": [
"next/babel",
"#babel/preset-env"
],
"plugins": []
}
I'm new to jest, so I'm not sure if I'm doing something wrong
In the jest.config file, you need to add the following to the moduleNameMapper attribute:
"react-markdown": "<rootDir>/node_modules/react-markdown/react-markdown.min.js"
So effectively, your moduleNameMapper should really look like this:
...
moduleNameMapper: {
'next/router': '<rootDir>/__mocks__/next/router.js',
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
},
...
Good luck!

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>
}

Test suits failed with "SyntaxError: Unexpected token 'export" ' react typescript using jest

i setup jest and enzyme in my react-typescript project. In this project i'm not using babel.
i tried to run basic component and its working well.
After that i added another component,and added our custom react-typescript based lib in this component(cc-react-common-lib).
when i include cc-react-common-lib, jest throws following error
SyntaxError: Unexpected token 'export'
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/convertcart/projects/intelli-blocks/node_modules/cc-react-common-lib/lib/index.js:1
export { default as TableSpaced } from './general/table-spaced';
^^^^^^
SyntaxError: Unexpected token 'export'
1 | /* eslint-disable jsx-a11y/control-has-associated-label */
2 | import React, { useState, useEffect } from 'react';
> 3 | import {
| ^
4 | TextField,
5 | useAjaxForm,
6 | Spacer,
I try to solve this error past1 week, but i can't find any solution
jest.config.js:
module.exports = {
// The root of your source code, typically /src
// `<rootDir>` is a token Jest substitutes
roots: ['<rootDir>'],
// Jest transformations -- this adds support for TypeScript
// using ts-jest
// transform: {
// "^.+\\.tsx?$": "ts-jest"
// },
preset: 'ts-jest',
// maxConcurrency:30,
// Runs special logic, such as cleaning up components
// when using React Testing Library and adds special
// extended assertions to Jest
// setupFilesAfterEnv: [
// "#testing-library/react/cleanup-after-each",
// "#testing-library/jest-dom/extend-expect"
// ],
// Test spec file resolution pattern
// Matches parent folder `__tests__` and filename
// should contain `test` or `spec`.
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
// Module file extensions for importing
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
snapshotSerializers: ['enzyme-to-json/serializer'],
setupFilesAfterEnv: ['<rootDir>/setupEnzyme.ts'],
};
setupEnzyme.js:
/* eslint-disable import/no-extraneous-dependencies */
import Enzyme from 'enzyme';
import ReactSixteenAdapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new ReactSixteenAdapter() });
Update: when i add following lines in jest.confi.js file
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
following Error message coming:
● Test suite failed to run
SyntaxError: /home/convertcart/projects/intelli-blocks/client/__tests__/editblock.test.tsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:29):
6 | console.log("Edit block test");
7 | it('Renders and Simulates Click Event ', () => {
> 8 | const Wrapper = shallow(<EditBlock />);
| ^
9 | const checkbox = () => Wrapper.find({ type: 'checkbox' });
10 | expect(checkbox().props().checked).toBe(false);
11 | checkbox().simulate('change', { target: { checked: true } });
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
at Parser._raise (../node_modules/#babel/parser/src/parser/error.js:60:45)
at Parser.raiseWithData
if you are running the test via a code editor plugin, try configuring the plugin test command within the editor to ensure the plugin executes the right command.
for e.g. i am using vscode, jestrunner plugin, and yarn package manager. so i included the following line inside my workspace settings.json file:
{
"jestrunner.jestCommand": "yarn react-scripts test"
}
the same error got resolved. hope it works for you :)

Resources