Babel fails with class-validator in NX Library - reactjs

I have an NX Typescript library which pulls in 'class-validators'.
The initial error I've ran into is
Support for the experimental syntax 'decorators-legacy' isn't currently enabled
So I've added this to my babel.config.json:
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
The next error I get is
Unexpected token, expected "{"
........
node_modules/#nrwl/web/src/utils/web-babel-loader.js)
in all my TypeScript files. I'm assuming babel is expecting JavaScript, so I've added
"presets": [
"#babel/preset-typescript"
],
To my babel.config.json. Now the issue I get with any class that uses class-validator's decorators (#IsDefined(), #IsNotNull(), etc...)
Module parse failed: Unexpected token (10:8)
File was processed with these loaders:
* ../../../node_modules/#nrwl/web/src/utils/web-babel-loader.js
You may need an additional loader to handle the result of these loaders.
I'm using an NX Workspace, and this is a plain TypeScript library... I'm not 100% sure what's going wrong here. When I run my NestJS server with this library it compiles and runs fine. But for some reason when I run the ReactJS Application, it fails with this error.
Any help is greatly appreciated!
EDIT:
Working babel.config.json
{
"babelrcRoots": [
"*"
],
"presets": [
"#babel/preset-typescript",
"#babel/preset-env"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"legacy": true
}
],
[
"#babel/plugin-transform-runtime"
]
]
}

Related

React - StoryBook - Error importing my components from node_modules

I have a project in React that contains quite a few components and I wanted to install StoryBook to be able to consult them.
For this I have installed StoryBook as a project outside my main project, leaving the folder structure as follows:
c:\development\MyProject
c:\development\StoryBook
Inside StoryBook I have added the following 'import' inside the Button.stories.jsx file that manages the buttons section that comes by default in the installation.
import SmallButton from 'MyProject/Buttons/SmallButton';
For this to work and to be able to import my component I have created a symbolic link inside the node_modules folder inside the StoryBook project.
c:\development\StoryBook\node_modules\MyProject <== symbolic link to c:\development\MyProject\src
When I start StoryBook with yarn storyboook it finds my component file but gives the following error that I can't resolve:
ERROR in ../MyProject/src/components/VSNButtons/SmallButton/index.js 10:12
Module parse failed: Unexpected token (10:12)
File was processed with these loaders:
* ./node_modules/#storybook/preset-create-react-app/node_modules/#pmmmwh/react-refresh-webpack-plugin
/loader/index.js
You may need an additional loader to handle the result of these loaders.
| const className = "ep-action " + (this.props.disabled ? "disabled " : " ") + (this.props.className || "");
| return (
> <span className={className} onClick={this.props.onClickHandle}>
| <span>
| <i className={"ep-action zmdi " + this.props.iconClass}></i>
# ./src/stories/atoms/buttons/Button.stories.jsx 150:0-58
# ./src sync ^\.(?:(?:^|[\\/]|(?:(?:(?!(?:^|[\\/])\.).)*?)[\\/])(?!\.)(?=.)[^\\/]*?\.stories\.(js|jsx|ts|tsx))$
# ./generated-stories-entry.js
# multi ./node_modules/#storybook/preset-create-react-app/node_modules/#pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js ./node_modules/#storybook/preset-create-react-app/node_modules/#pmmmwh/react-refresh-webpack-plugin/client/ErrorOverlayEntry.js ./nod
e_modules/#storybook/core-server/node_modules/#storybook/core-client/dist/esm/globals/polyfills.js ./node_modules/#storybook/core-server/node_modules/#storybook/core-client/dist/esm/globals/globals.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=fal
se&noInfo=undefined ./storybook-init-framework-entry.js ./node_modules/#storybook/addon-docs/dist/esm/frameworks/common/config.js-generated-config-entry.js ./node_modules/#storybook/addon-docs/dist/esm/frameworks/react/config.js-generated-config-entry.js ./node_modules/
#storybook/react/dist/esm/client/preview/config-generated-config-entry.js ./node_modules/#storybook/addon-links/dist/esm/preset/addDecorator.js-generated-config-entry.js ./node_modules/#storybook/addon-actions/dist/esm/preset/addDecorator.js-generated-config-entry.js ./
node_modules/#storybook/addon-actions/dist/esm/preset/addArgs.js-generated-config-entry.js ./node_modules/#storybook/addon-backgrounds/dist/esm/preset/addDecorator.js-generated-config-entry.js ./node_modules/#storybook/addon-backgrounds/dist/esm/preset/addParameter.js-g
enerated-config-entry.js ./node_modules/#storybook/addon-measure/dist/esm/preset/addDecorator.js-generated-config-entry.js ./node_modules/#storybook/addon-outline/dist/esm/preset/addDecorator.js-generated-config-entry.js ./node_modules/#storybook/addon-interactions/dist
/esm/preset/argsEnhancers.js-generated-config-entry.js ./.storybook/preview.js-generated-config-entry.js ./generated-stories-entry.js
**File Configuration of StoryBook (main.js) **
module.exports = {
stories: [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
staticDirs: ["../public"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/preset-create-react-app",
"#storybook/addon-interactions",
],
features: {
postcss: false
},
framework: "#storybook/react",
core: {
builder: "webpack4",
}
};
And .babelrc of StoryBook
{
"sourceType": "unambiguous",
"presets": [
[
"#babel/preset-env",
{
"shippedProposals": true,
"loose": true
}
],
"#babel/preset-typescript"
],
"plugins": [
"#babel/plugin-transform-shorthand-properties",
"#babel/plugin-transform-block-scoping",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
[
"#babel/plugin-proposal-private-methods",
{
"loose": true
}
],
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-syntax-dynamic-import",
[
"#babel/plugin-proposal-object-rest-spread",
{
"loose": true,
"useBuiltIns": true
}
],
"#babel/plugin-transform-classes",
"#babel/plugin-transform-arrow-functions",
"#babel/plugin-transform-parameters",
"#babel/plugin-transform-destructuring",
"#babel/plugin-transform-spread",
"#babel/plugin-transform-for-of",
"babel-plugin-macros",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
[
"babel-plugin-polyfill-corejs3",
{
"method": "usage-global",
"absoluteImports": "core-js",
"version": "3.18.3"
}
]
]
}
Does anyone know what would be the solution to apply to solve this problem?
Or maybe it's because I can't import components from other projects.
Thank you very much.
PD: Sorry my english, I used GoogleTranslate to help me.

Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled in react js

i am trying run my react application using npm start commamnd and installed both #babel/preset-react and #babel/plugin-syntax-jsx. but i am running this react application getting following error.
Support for the experimental syntax 'jsx' isn't currently enabled (7:9):
6 | const PostCodeLookup = props => {
> 7 | return <PostcodeLookup {...props} />
| ^
8 |
9 | };
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.
It's hard to tell with no knowledge on how you bootstrapped your app, as jaybhatt said before.
If you used react-create-app probably you messed with packages and ended up in a inconsistent state. Try to reset your app. Creating a app on another folder and migrating your code there is an option (I did that a couple of times :) !).
If you created the app structure "by hand", check if you have "#babel/preset-react" set also on webpack config:
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: { presets: ['#babel/env', '#babel/preset-react'] },
},
Can you tell where you bootstrapped your application from? (Create React App or something like that?)
Also, you need to have a .babelrc or babel.config.js(on) file with these contents, just installing the packages won't work.
Putting an example below for how your babel.config.json should look like. Please remove any extra plugins from below example in case you use it.
{
"presets": [
[
"#babel/preset-env",
{
"modules": false,
"targets": {
"node": "current"
}
}
],
"#babel/preset-react"
],
"env": {
"test": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"spec": true
}
]
]
}
},
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"spec": true
}
],
"#babel/plugin-proposal-object-rest-spread"
]
}

babel-plugin-styled-components not work with preset-typescript

I use Typescript in my project and use Babel7 preset-typescript to transform Ts. And I want to add babel-plugin styled-components to my project, but it does not show component display class name
Another option for typescript styled component tooling is typescript-plugin-styled-components. But it seems to work with webpack typescript loader. Since I use babel7 to transform TS so I dont use TS loader in webpack
Here is my babel config:
{
"presets": [
[
"#babel/preset-env",
{
"modules": false
}
],
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
"babel-plugin-styled-components",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-syntax-dynamic-import",
"react-hot-loader/babel"
],
"env": {
"production": {
"only": ["src"],
"plugins": [
"babel-plugin-styled-components",
"lodash",
"transform-react-remove-prop-types",
"#babel/plugin-transform-react-inline-elements",
"#babel/plugin-transform-react-constant-elements"
]
}
}
}
Could you guys show me the way to fix my babel-plugin-styled-components? Thanks
There is another solution for TS. Try this one: github.com/Igorbek/typescript-plugin-styled-components

React-Native 0.57: 'Can't find variable: require' with metro-react-native-babel-preset

I started a multiplatform project with code sharing between react-native and react-js.
So I have a webpack setup for browser/Electron, and a react-native 0.57 setup for Android/iOS.
The problem I'm having right now is the following:
Can't find variable: require
It might be a very bald question, but do I need anything else? I read, that React-native should support require by itself, but couldn't find anything related to this setup yet.
.babelrc
{"presets": ["module:metro-react-native-babel-preset"]}
I'm also using #babel/polyfill and #babel/runtime on browser side, but I wonder if they would interfere.
Got the solution, my .babelrc was okay, but the packager cached the very first wrong one so I had to start the packager as:
react-native start --reset-cache
After looking at below github issue it looks like the issue is caused by corejs option #babel/plugin-transform-runtime, So replace it by #babel/polyfil
https://github.com/facebook/react-native/issues/21048
.babelrc config for ref
{
"presets": [
"module:metro-react-native-babel-preset",
],
"plugins": [
"react-require",
[
"module-resolver",
{
"root": [
"./src",
"./assets"
],
"alias": {
"app": "./src",
"assets": "./assets"
}
}
],
[
"babel-plugin-require-context-polyfill",
{
"alias": {
"app": "./src"
}
}
],
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-transform-flow-strip-types",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": false
}
],
[
"#babel/plugin-transform-runtime",
{
}
],
],
"sourceMaps": true
}
Install Babel polyfill 7 "#babel/polyfill": "^7.0.0"
And import that in App component
import '#babel/polyfill'
It seems that react-native start --reset-cache works.

Babel will not compile .test.js files while running Jest

While running yarn run jest --no-cache, An error is being thrown that says:
SyntaxError: Unexpected token import
My best guess is that babel is not reaching this this test file. Is their something special I need to include in .babelrc?
path:
/src/tests/LandingPage.test.js
test file:
import React from 'react';
import ReactShallowRenderer from 'react-test-renderer/shallow';
import LandingPage from '../../components/LandingPage';
test('Should render LandingPage correctly', () => {
const renderer = new ReactShallowRenderer();
renderer.render(<LandingPage />);
expect(renderer.getRenderOutput()).toMatchSnapshot();
});
.babelrc :
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
Thanks #hannad rehmann for the nudge in the right direction here is the solution that worked for me.
Install babel-jest
yarn add babel-jest --dev
Configure .babelrc for test env
Jest automatically sets your Env to test, so duplicate whatever config you want to the test env.
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"env": {
"test": {
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
}
}
Add jest.config.json to project root
{
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
Finally, let your test script know where to find config file
I just added it to my test script in package.json, but you can also just run this in the command line.
"scripts": {
"test": "jest --config=jest.config.json --watch"
},
oh. this issue had me waste so many days. here is what you need to do.
before that check these files.
1) .babelrc install corresponding modules and add them to package.json
define different env support as your jest always changes NODE_ENV to "test"
{
"presets": [
[
"env",
{ "modules": false }],
"react"
],
"plugins": [
"react-hot-loader/babel",
"transform-object-rest-spread",
"transform-class-properties",
"dynamic-import-webpack"
],
"env":{
"test":{
"presets": [
"env",
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"dynamic-import-webpack"
]}
}
}
2) add this to your package.json
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"automock": false,
"transform": {
"^.+\\.jsx?$": "<rootDir>/node_modules/babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/"
],
"transformIgnorePatterns": [
"/node_modules/"
],
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"modulePathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"coverageReporters": [
"json",
"lcov",
"text"
]
}
What I understood about this problem is that Jest will change your NODE_ENV to "test" and Babel doesn't have any configuration for this env, we normally define Babel config for development and production env. When there is no babel transpilation, import keyword actually becomes undefined as it actually doesn't exist in JS context.
For anyone looking for solutions, in my case the problem turned out that I had my NODE_ENV environment variable configured to development for some reason.
Now JEST only sets the env to test if NODE_ENV is not defined yet, otherwise it'll use the value of NODE_ENV. This means if you have added in your .babelrc or babel.config file a dedicated part for the test (something like below), it will be ignored,and defaults (or the one matching your NODE_ENV) will be used instead!
{
...
"env": {
"test": { presets: [ "#babel/preset-env" ] }
}
...
}
So if it looks like JEST does not transform your test files (which one of a sign can be a SyntaxError: Cannot use import statement outside a module when running tests reated to your test.js or spec.js file) I'd recommend to check if you have NODE_ENV defined.
Use the env command (on MacOS and Linux or the appropriate command for your environment) to check the configured environment variables. If you have it already configured to something (other than test) you need to either remove that or prepend your jest commands with appropriate override: env NODE_ENV=test jest.
I hope it'll help others. Took me good few hours to figure out what was going on...

Resources