React - StoryBook - Error importing my components from node_modules - reactjs

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.

Related

SyntaxError: Unexpected token export while running tests in Jest with components having amcharts4

Geeting error: Unexpected token export while running tests in Jest with components having amcharts4
export { System, system } from "./.internal/core/System";
^^^^^^
SyntaxError: Unexpected token export
> 1 | import * as am4core from "#amcharts/amcharts4/core";
| ^
2 | import * as am4charts from "#amcharts/amcharts4/charts";
3 | import * as am4maps from "#amcharts/amcharts4/maps";
4 | import am4geodata_worldLow from "#amcharts/amcharts4-geodata/worldLow";
"jest": "24.9.0"
"#amcharts/amcharts4": "^4.10.19"
"typescript": "^3.9.5"
Following is jest config in the package.json file :(Using create-react-app for the project & ejected it)
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom",
"<rootDir>\\src\\__mocks__\\dom.js",
"<rootDir>\\src\\__mocks__\\reactrouter.js"
],
"setupFilesAfterEnv": [
"#testing-library/jest-dom/extend-expect"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jest-environment-jsdom-fourteen",
"transform": {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"node_modules/(?!#amcharts/amcharts4/)",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [
"<rootDir>/src/",
"<rootDir>/node_modules/"
],
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/src/__mocks__/styleMock.js"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
}
Cause: babel-jest uses babel configuration that is loaded based on the location of the file that is going to be transformed. After ejecting create-react-app your package.json probably contains:
"babel": {
"presets": [
"react-app"
]
}
which makes import/export statements work for your files, but #amcharts/amcharts4 does not have that setting in its package.json nor does it have .babelrc and so no import/export transformation takes place.
Solution: You can update your Jest config to transform #amcharts in a more specific way:
Add relevant babel plugin: npm install -D #babel/plugin-transform-modules-commonjs
Update jest config in your package.json - redirect #amcharts transformation to custom transformer. (I also changed transformIgnorePatterns so that they work for Windows.)
"transform": {
"#amcharts[/\\\\].+\\.(js|jsx|ts|tsx)$": "<rootDir>/config/jest/babelTransformImportExport.js",
"^.+\\.(js|jsx|ts|tsx)$": "babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"node_modules[/\\\\](?!#amcharts[/\\\\]amcharts4[/\\\\])",
"^.+\\.module\\.(css|sass|scss)$"
],
Create config/jest/babelTransformImportExport.js:
const babelJest = require("babel-jest");
module.exports = babelJest.createTransformer({
plugins: [require.resolve("#babel/plugin-transform-modules-commonjs")],
babelrc: false,
configFile: false,
});
Tests should be running now.
Edit: As Subrato Patnaik mentioned (using amcharts with jest), amcharts use APIs such as SVGPathElement which aren't yet available in Jest test environment (JSDOM - issue #2128). In other words, your tests won't probably work, if you're using standard mounting. But they might work if you are using e.g. enzyme and its shallow rendering.
If you don't use enzyme or it doesn't work, then as the last resort, you can try to simply define missing APIs in a minimalistic way and see whether it is sufficient:
Change setupFiles in jest config to:
"setupFiles": [
"react-app-polyfill/jsdom",
"<rootDir>/config/jest/setup.js"
],
Create config/jest/setup.js:
class SVGGraphicsElement extends SVGElement {}
class SVGGeometryElement extends SVGGraphicsElement {}
class SVGPathElement extends SVGGeometryElement {}
Object.assign(global, {
SVGGraphicsElement,
SVGGeometryElement,
SVGPathElement,
});
PS: If you are using pnpm instead of npm/yarn, then you will need to update transformIgnorePatterns to:
"node_modules[/\\\\](?!(|\\.pnpm[/\\\\]#amcharts.*node_modules[/\\\\])#amcharts[/\\\\]amcharts4[/\\\\])",
otherwise the old regexp would match (and therefore ignore) paths such as node_modules/.pnpm/#amcharts+amcharts4#4.10.21/node_modules/#amcharts/amcharts4/core.js

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 fails with class-validator in NX Library

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

Issue with minifying transpiled `jsx` code into browser readable format

I have to host a js file on a server to be imported into any html page.
We have written some react components for the same purpose.
When we import the un-minified js file in the html, it works fine.
But, when we use the minified js file, it doesn't work. That means, it doesn't show anything in the browser.
We are using webpack for bundling the react components. yarn build
Babel-loaders to transpile the jsx code to js
I have tried to manually transpile the jsx code and then minify it. In this case the minified file also works.
But, it doesn't work when I transpile it through the my project config.
The difference between the manually minified and the projects minified file was that the manually minified file has the reference of the js files where React components are written.
.babelrc
{
"presets": [
["latest"],
"es2015",
"flow",
"react",
"stage-2",
],
"plugins": [
"syntax-dynamic-import",
],
"env": {
"production": {
"plugins": [
"transform-react-remove-prop-types",
"transform-react-inline-elements"
]
},
"development": {
"plugins": [
"transform-react-jsx-source"
]
},
"test": {
"presets": [
["latest"],
"es2015",
"flow",
"react",
"stage-2",
],
"plugins": [
"syntax-dynamic-import",
"transform-react-jsx-source"
]
}
}
}
webpack.config.js
const path = require('path');
const paths = require('./webpack.paths.js');
const loaders = require('./webpack.loaders.js');
const plugins = require('./webpack.plugins.js');
module.exports = {
entry: [path.resolve(paths.embed, 'index.js')],
output: {
path: paths.productionRoot,
filename: 'filename.js',
},
resolve: {
extensions: ['.js', '.jsx'],
alias: Object.assign({}, {
'react': 'preact-compat',
'react-dom': 'preact-compat',
}),
},
module: {
loaders: [
loaders.eslint,
loaders.iFrameJs,
loaders.css,
],
},
plugins: [
plugins.environmentVariables,
],
};
I guess the problem with .babelrc file configuration.
Would you please give a try using #babel/preset-react as recommended on babeljs site? https://babeljs.io/docs/en/babel-preset-react
Example :
npm install --save-dev #babel/preset-react
.babelrc file (Usage)
{ "presets": ["#babel/preset-react"] }
I changed the webpack config and removed the below piece of code.
alias: Object.assign({}, {
'react': 'preact-compat',
'react-dom': 'preact-compat',
}),
The react and preact version mismatch was causing the problem.
New webpack config
module.exports = {
entry: [path.resolve(paths.embed, 'index.js')],
output: {
path: paths.productionRoot,
filename: 'termly.js',
},
resolve: {
extensions: ['.js'],
},
module: {
loaders: [
loaders.eslint,
loaders.js,
loaders.css,
],
},
plugins: [
plugins.environmentVariables,
],
};
This solved the issue

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.

Resources