WebSocket connection to 'wss://localhost:3000/sockjs-node' failed: - reactjs

I am working in a react application (Below Package.json)
{
"name": "seed",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
"dependencies": {
"#ckeditor/ckeditor5-adapter-ckfinder": "23.1.0",
"#ckeditor/ckeditor5-alignment": "23.1.0",
"#ckeditor/ckeditor5-autoformat": "23.1.0",
"#ckeditor/ckeditor5-basic-styles": "23.1.0",
"#ckeditor/ckeditor5-block-quote": "23.1.0",
"#ckeditor/ckeditor5-build-classic": "23.1.0",
"#ckeditor/ckeditor5-ckfinder": "23.1.0",
"#ckeditor/ckeditor5-dev-utils": "^23.5.1",
"#ckeditor/ckeditor5-dev-webpack-plugin": "^23.5.1",
"#ckeditor/ckeditor5-easy-image": "23.1.0",
"#ckeditor/ckeditor5-editor-classic": "23.1.0",
"#ckeditor/ckeditor5-editor-decoupled": "23.1.0",
"#ckeditor/ckeditor5-font": "23.1.0",
"#ckeditor/ckeditor5-heading": "23.1.0",
"#ckeditor/ckeditor5-highlight": "23.1.0",
"#ckeditor/ckeditor5-image": "23.1.0",
"#ckeditor/ckeditor5-link": "23.1.0",
"#ckeditor/ckeditor5-list": "23.1.0",
"#ckeditor/ckeditor5-media-embed": "23.1.0",
"#ckeditor/ckeditor5-paste-from-office": "23.1.0",
"#ckeditor/ckeditor5-react": "3.0.0",
"#ckeditor/ckeditor5-real-time-collaboration": "23.1.0",
"#ckeditor/ckeditor5-remove-format": "23.1.0",
"#ckeditor/ckeditor5-table": "23.1.0",
"#ckeditor/ckeditor5-theme-lark": "23.1.0",
"#date-io/date-fns": "1.3.13",
"#material-ui/core": "4.9.10",
"#material-ui/icons": "^4.9.1",
"#material-ui/lab": "^4.0.0-alpha.56",
"#material-ui/pickers": "^3.2.10",
"#types/pdfjs-dist": "^2.1.5",
"aws-amplify": "^3.0.22",
"babel-polyfill": "6.26.0",
"connected-react-router": "^6.3.2",
"date-fns": "^2.14.0",
"env-cmd": "8.0.2",
"formik": "2.1.5",
"history": "4.7.2",
"juice": "^7.0.0",
"lodash": "^4.17.11",
"pdf-viewer-reactjs": "^2.0.7",
"pdfjs-dist": "2.4.456",
"raw-loader": "^4.0.1",
"react": "^16.8.3",
"react-dom": "^16.8.3",
"react-hot-toast": "^1.0.2",
"react-intl": "2.7.2",
"react-redux": "^6.0.1",
"react-router": "4.3.1",
"react-router-dom": "4.3.1",
"react-scripts": "^2.1.5",
"redux": "4.0.1",
"redux-persist": "5.10.0",
"redux-persist-transform-filter": "^0.0.20",
"redux-saga": "^1.0.2",
"styled-components": "4.1.1",
"superagent": "4.0.0",
"typesafe-actions": "^3.0.0",
"yup": "^0.28.3"
},
"scripts": {
"start": "HTTPS=true REACT_APP_ENV=local react-app-rewired start",
"start:windows": "set HTTPS=true&&set REACT_APP_ENV=local&&react-app-rewired start",
"build": "env-cmd .env.${REACT_APP_ENV} react-app-rewired build",
"build:staging": "REACT_APP_ENV=staging env-cmd .env.staging react-app-rewired build ",
"build:qa": "REACT_APP_ENV=qa env-cmd .env.qa react-app-rewired build ",
"build:qaint": "REACT_APP_ENV=qaint env-cmd .env.qaint react-app-rewired build ",
"build:euat": "REACT_APP_ENV=euat env-cmd .env.euat react-app-rewired build ",
"test": "react-app-rewired test --maxWorkers=4",
"test:ci": "react-app-rewired test --maxWorkers=4 --all --coverage",
"eject": "react-app-rewired eject",
"analyze": "env-cmd .env.${REACT_APP_ENV} react-app-rewired build --analyze-bundle",
"test:coverage": "npm run test -- --coverage",
"generate": "plop --plopfile scripts/generators/index.js",
"lint": "eslint 'src/**/*.{js,ts,tsx}'",
"lint:fix": "eslint 'src/**/*.{js,ts,tsx}' --fix",
"lint-style": "stylelint 'src/**/*.style.{ts,tsx}' 'src/**/style.{ts,tsx}'",
"cypress:run": "sudo docker-compose -f docker-compose-cypress.yml run e2e-chrome"
},
"browserslist": [
">0.2%",
"not dead",
"not ie < 11",
"not op_mini all"
],
"jest": {
"collectCoverageFrom": [
"src/**/*.js",
"!src/**/*.test.js",
"!src/**/actions.js",
"!src/**/index.js",
"!src/**/serviceWorker.js",
"!src/**/*.wrap.js",
"!src/index.js",
"!src/tempPolyfills.js",
"!src/setupTests.js",
"!src/redux/reducers.js",
"!src/redux/sagas.js",
"!src/redux/store.js",
"!src/**/mocks/**",
"!src/redux/reducers.ts",
"!src/redux/sagas.ts"
],
"coverageThreshold": {
"global": {
"statements": 0,
"branches": 0,
"functions": 0,
"lines": 0
}
},
"snapshotSerializers": [
"<rootDir>/node_modules/enzyme-to-json/serializer"
],
"setupFiles": [
"core-js"
]
},
"bundlesize": [
{
"path": "./build/static/js/*.js",
"maxSize": "200 kB"
}
],
"devDependencies": {
"#types/cheerio": "^0.22.10",
"#types/enzyme": "^3.1.15",
"#types/enzyme-react-intl": "^2.0.0",
"#types/history": "^4.7.2",
"#types/jest": "^23.3.12",
"#types/lodash": "^4.14.119",
"#types/node": "^10.12.18",
"#types/pdf-viewer-reactjs": "^2.0.0",
"#types/react": "^16.8.3",
"#types/react-dom": "^16.0.11",
"#types/react-intl": "^2.3.15",
"#types/react-redux": "^6.0.12",
"#types/react-router": "^4.4.3",
"#types/react-router-dom": "^4.3.1",
"#types/react-test-renderer": "^16.0.3",
"#types/redux-mock-store": "^1.0.2",
"#types/styled-components": "^4.1.5",
"#types/superagent": "^3.8.6",
"#types/webpack-env": "^1.13.6",
"#types/yup": "^0.26.34",
"#typescript-eslint/eslint-plugin": "^1.6.0",
"#typescript-eslint/parser": "^1.6.0",
"babel-plugin-styled-components": "1.8.0",
"enzyme": "3.7.0",
"enzyme-adapter-react-16": "1.15",
"enzyme-react-intl": "^2.0.6",
"enzyme-to-json": "3.3.4",
"eslint-config-prettier": "4.1.0",
"eslint-plugin-import": "2.14.0",
"eslint-plugin-jest": "22.0.0",
"eslint-plugin-jsx-a11y": "6.1.2",
"eslint-plugin-mysticatea": "4.2.4",
"eslint-plugin-prefer-object-spread": "1.2.1",
"eslint-plugin-prettier": "3.0.0",
"eslint-plugin-react": "7.11.1",
"husky": "^4.2.5",
"mockdate": "^3.0.2",
"plop": "2.1.0",
"prettier": "1.15.1",
"react-app-rewire-webpack-bundle-analyzer": "1.0.1",
"react-app-rewired": "2.1.0",
"react-test-renderer": "16.10",
"redux-mock-store": "^1.5.4",
"redux-saga-test-plan": "^4.0.0-beta.2",
"stylelint": "^9.10.1",
"stylelint-config-prettier": "^4.0.0",
"stylelint-config-standard": "^18.2.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-declaration-strict-value": "^1.1.2",
"stylelint-processor-styled-components": "^1.5.2",
"typescript": "^3.2.2",
"wait-on": "^3.2.0",
"webpack-manifest-plugin": "^2.0.4"
}
}
Below config-overrides.js
const { styles } = require( '#ckeditor/ckeditor5-dev-utils' );
module.exports = {
webpack: function override(config, env) {
const analyzeBundle = process.argv.indexOf('--analyze-bundle') !== -1;
if (analyzeBundle) {
const rewireWebpackBundleAnalyzer = require('react-app-rewire-webpack-bundle-analyzer');
config = rewireWebpackBundleAnalyzer(config, env, {
analyzerMode: 'static',
reportFilename: 'report.html',
});
}
// Fix strange issue with webpack build
// details here: https://stackoverflow.com/questions/60407393/create-react-app-production-build-runtime-error-cannot-read-property-call-of
// TODO: maybe update webpack to fix while keeping import optimization
config.optimization.sideEffects = false;
// Customize webpack config here
console.log("Loading Custom config for Webpack, rebuilding ckeditor");
const oneOfIndex = config.module.rules.findIndex(item => {
return item.hasOwnProperty("oneOf");
});
oneOf = config.module.rules[oneOfIndex].oneOf;
// Add the SVG and CSS loaders to the oneOf array
const additions = [
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
use: ["raw-loader"]
},
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/,
use: [
{
loader: "style-loader",
},
{
loader: "postcss-loader",
options: styles.getPostCssConfig({
themeImporter: {
themePath: require.resolve("#ckeditor/ckeditor5-theme-lark")
},
minify: true
})
}
]
}
];
additions.forEach((item) => {
oneOf.push(item);
});
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
// Modify cssRegex
let loader;
loader = oneOf.find(item => {
if (item.test !== undefined)
return item.test.toString() === cssRegex.toString();
});
loader.exclude = [cssModuleRegex, /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/];
// Modify cssModuleRegex
loader = oneOf.find(item => {
if (item.test !== undefined)
return item.test.toString() === cssModuleRegex.toString();
});
loader.exclude = [/ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/];
// Modify file-loader
loader = oneOf.find(item => {
if (item.loader !== undefined)
return (
item.loader.toString() === require.resolve("file-loader").toString()
);
});
loader.exclude = [
/\.(js|mjs|jsx|ts|tsx)$/,
/\.html$/,
/\.json$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/
];
config.module.rules[oneOfIndex].oneOf = oneOf;
return config;
},
devServer: function(configFunction) {
// Return the replacement function for create-react-app to use to generate the Webpack
// Development Server config. "configFunction" is the function that would normally have
// been used to generate the Webpack Development server config - you can use it to create
// a starting configuration to then modify instead of having to create a config from scratch.
return function(proxy, allowedHost) {
// Create the default config by calling configFunction with the proxy/allowedHost parameters
const defaultConfig = configFunction(proxy, allowedHost);
return {
...defaultConfig,
hot: true,
historyApiFallback: true,
// Allow mounting react apps from a page served by the backend.
headers: {
'Access-Control-Allow-Origin': 'http://localhost:8080',
},
};
};
},
};
I am trying to load another react application as a microfront end using :
I ve tested the imported microfront end in a simple react app (container) and everything went well
import React, {useCallback, useEffect} from 'react';
import {History} from 'history';
interface MicroFrontendProps {
history?: History;
name: string;
host: string | undefined;
}
const MicroFrontend: React.FC<MicroFrontendProps> = ({history, name, host,}) => {
const renderMicroFrontend = useCallback(() => {
(window as any)[`render${name}`](`${name}-container`, history);
}, [name, history]);
useEffect(() => {
const scriptId = `micro-frontend-script-${name}`;
if (document.getElementById(scriptId)) {
renderMicroFrontend();
} else {
fetch(`${host}/asset-manifest.json`)
.then(res => res.json())
.then(manifest => {
const promises = Object.keys(manifest.files)
.filter(key => key.endsWith('.js'))
.reduce((sum, key) => {
sum.push(
new Promise(resolve => {
const path = `${host}${manifest.files[key]}`;
const script = document.createElement('script');
if (key === 'main.js') {
script.id = scriptId;
}
script.onload = () => {
resolve();
};
script.crossOrigin = '';
script.src = path;
document.body.after(script);
}),
);
return sum;
}, [] as any);
Promise.allSettled(promises).then(() => {
renderMicroFrontend();
});
});
}
return () => {
(window as any)[`unmount${name}`](`${name}-container`);
};
}, [renderMicroFrontend, host, name]);
return <main id={`${name}-container`} />;
};
export default MicroFrontend;
When I am importing the app, when I go to a link which loads it I am getting this error (the imported app is rendred but server shuts down) :
webpackHotDevClient.js:60 WebSocket connection to 'wss://localhost:3000/sockjs-node' failed:
./node_modules/react-dev-utils/webpackHotDevClient.js # webpackHotDevClient.js:60
webpackHotDevClient.js:76 The development server has disconnected.
Refresh the page if necessary.
Do you have any idea about this error ?
Thanks

Related

Error in vite#4.x + ant#3.x + react#16 : Unknown theme type: undefined, name: undefined

I am trying to migrate an old project into vite and I'm very close to success. There is just one bug which occurs in one of the javascript files of ant design when I deploy the app on server.
bug.
This is happening in the following function exported by antd#3.x
export function withSuffix(name, theme) {
switch (theme) {
case "fill":
return name + "-fill";
case "outline":
return name + "-o";
case "twotone":
return name + "-twotone";
default:
throw new TypeError("Unknown theme type: " + theme + ", name: " + name);
}
}
icons.forEach(function (icon) {
_this2.definitions.set(withSuffix(icon.name, icon.theme), icon);
});
I think this forEach loop is running on an array of undefined ([undefined, undefined..]) but I can't figure out why. I suspect it is due to some configuration I'm missing in my vite file or some other configuration.
If I change the code to this,
export function withSuffix(name, theme) {
switch (theme) {
case "fill":
return name + "-fill";
default:
case "outline":
return name + "-o";
case "twotone":
return name + "-twotone";
}
}
My project runs perfectly on local as well as on server. Here are my package.json and vite.config.ts
`{
"name": "ta",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"start": "vite --mode local",
"start:dev": "vite --mode local-development",
"start:qa": "vite --mode local-qa",
"build:dev": "tsc && vite build --base=/ta-admin --mode development",
"build:qa": "tsc && vite build --base=/ta-admin --mode qa",
"build:staging": "tsc && vite build --base=/admin --mode staging",
"build:prod": "tsc && vite build --base=/admin --mode production",
"preview": "vite preview"
},
"dependencies": {
"#ant-design/plots": "^1.2.4",
"#material-ui/core": "^4.4.0",
"#material-ui/icons": "^4.2.1",
"#reduxjs/toolkit": "^1.9.2",
"antd": "^3.19.3",
"antd-virtual-select": "^1.1.2",
"axios": "^1.3.0",
"file-saver": "^2.0.5",
"history": "^4.10.1",
"html2canvas": "^1.4.1",
"immutability-helper": "^3.0.1",
"jquery": "^3.6.3",
"jspdf": "^2.5.1",
"keycloak-js": "^20.0.3",
"less": "^4.1.3",
"loadable-components": "^2.2.3",
"lodash-decorators": "^6.0.1",
"lodash.difference": "^4.5.0",
"moment": "^2.29.4",
"popper.js": "^1.16.1",
"react": "^16.8.6",
"react-dnd": "^9.4.0",
"react-dnd-html5-backend": "^9.4.0",
"react-dom": "^16.8.6",
"react-html-parser": "^2.0.2",
"react-intl": "^2.9.0",
"react-intl-universal": "^2.6.11",
"react-monaco-editor": "^0.31.0",
"react-redux": "^8.0.5",
"react-router-dom": "^5.3.4",
"styled-components": "^5.3.6"
},
"devDependencies": {
"#types/node": "^18.11.18",
"#types/react": "^16.8.6",
"#types/react-dom": "^18.0.10",
"#types/react-router-dom": "^5.3.3",
"#vitejs/plugin-react": "^3.0.0",
"typescript": "^4.9.5",
"vite": "^4.0.0"
}
}
import { defineConfig, loadEnv } from "vite";
import react from "#vitejs/plugin-react";
const getApiHost = (npm_lifecycle_event: string) => {
switch (npm_lifecycle_event) {
default:
case "start":
return "http://localhost:8080";
}
};
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
const scriptArray = env?.npm_lifecycle_script?.split(" ") || [];
const basePortion = scriptArray.find((scriptPortion) => {
return scriptPortion.includes("--base");
});
let outDir = basePortion ? basePortion.split("/")[1] : "build";
const target = getApiHost(env.npm_lifecycle_event);
const runningLocally = mode.includes("local");
return {
plugins: [react()],
...(runningLocally
? {
define: {
global: {},
},
}
: {}),
server: {
port: 3000,
open: true,
proxy: {
"/api": {
target,
changeOrigin: true,
secure: false,
},
},
},
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
additionalData: "#root-entry-name: default;",
},
},
},
build: {
outDir,
commonjsOptions: {
transformMixedEsModules: true,
},
},
};
});

Property 'require' doesn't exist in react native error

I think this error from metro bundler,
here is the image for the error:
I try every solution on the net from the official react native GitHub issue.
also try deleting node modules
restart the cache
On the terminal, it didn't show any error but on the device, it threw an error. Any help?
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset',
'#babel/preset-typescript','#babel/preset-env'],
plugins: [
['#babel/plugin-proposal-class-properties'],
['module:react-native-dotenv',
{
moduleName: '#env',
path: '.env',
},
],
'react-native-reanimated/plugin',
[
'module-resolver',
{
root: ['./src/'],
alias: {
'#assets': './src/assets',
'#components': './src/components',
'#constants': './src/constants',
'#navigation': './src/navigations',
'#screens': './src/screens',
'#utils': './src/utils',
'#styles': './src/styles',
'#redux': './src/redux',
'#config': './src/config',
},
},
],
],
};
metro.config.js
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
jestConfig.ts
import mockAsyncStorage from '#react-native-async-storage/async-storage/jest/async-storage-mock';
import 'react-native-gesture-handler/jestSetup';
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
jest.mock('react-native-keyboard-controller', () => ({}));
jest.mock('react-native-bootsplash', () => {
return {
hide: jest.fn(),
show: jest.fn(),
};
});
jest.mock('#notifee/react-native', () => ({}));
jest.mock('#react-native-async-storage/async-storage', () => mockAsyncStorage);
jest.mock('axios', () => {
return {
create: () => {
return {
get: jest.fn(),
post: jest.fn(),
put: jest.fn(),
interceptors: {
request: {eject: jest.fn(), use: jest.fn()},
response: {eject: jest.fn(), use: jest.fn()},
},
};
},
};
});
export {};
package.json
{
"name": "name",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
"dependencies": {
"#notifee/react-native": "^7.2.0",
"#react-native-async-storage/async-storage": "^1.17.10",
"#react-native-masked-view/masked-view": "^0.2.8",
"#react-navigation/bottom-tabs": "^6.4.0",
"#react-navigation/native": "^6.0.13",
"#react-navigation/native-stack": "^6.9.1",
"#reduxjs/toolkit": "^1.8.6",
"#shopify/flash-list": "^1.3.1",
"#types/lodash": "^4.14.191",
"axios": "^1.2.1",
"babel-plugin-module-resolver": "^4.1.0",
"native-base": "^3.4.22",
"react": "18.1.0",
"react-native": "0.70.6",
"react-native-bootsplash": "^4.3.2",
"react-native-dotenv": "^3.4.2",
"react-native-fast-image": "^8.6.3",
"react-native-gesture-handler": "^2.7.1",
"react-native-keyboard-controller": "^1.4.2",
"react-native-modal": "^13.0.1",
"react-native-pager-view": "^6.1.2",
"react-native-pusher-push-notifications": "^2.5.1",
"react-native-reanimated": "^2.11.0",
"react-native-responsive-screen": "^1.4.2",
"react-native-safe-area-context": "3.3.2",
"react-native-screens": "^3.18.2",
"react-native-svg": "12.1.1",
"react-native-tab-view": "^3.3.4",
"react-native-vector-icons": "^9.2.0",
"react-native-webview": "^11.26.0",
"react-redux": "^8.0.4",
"redux": "^4.2.0",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.4.2",
"ts-jest": "^29.0.3"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"#babel/preset-typescript": "^7.18.6",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"#tsconfig/react-native": "^2.0.2",
"#types/jest": "29.0.3",
"#types/react": "^18.0.21",
"#types/react-native": "^0.70.6",
"#types/react-native-dotenv": "^0.2.0",
"#types/react-native-vector-icons": "^6.4.12",
"#types/react-test-renderer": "^18.0.0",
"#types/redux-logger": "^3.0.9",
"#types/redux-persist": "^4.3.1",
"#typescript-eslint/eslint-plugin": "^5.37.0",
"#typescript-eslint/parser": "^5.37.0",
"babel-jest": "29.0.3",
"babel-plugin-transform-require-context": "^0.1.1",
"eslint": "^7.32.0",
"jest": "29.0.3",
"metro-react-native-babel-preset": "0.72.3",
"react-native-typescript-transformer": "^1.2.13",
"react-test-renderer": "18.1.0",
"typescript": "^4.8.3"
},
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFiles": [
"./jestConfig.ts"
],
"transformIgnorePatterns": [
"node_modules/node_modules/react-native-responsive-screen/index.js"
]
}
}
This line:
import 'react-native-gesture-handler/jestSetup';
Should probably be something like:
import jestSetup from 'react-native-gesture-handler/jestSetup';
Check the documentation of the library how that import should work.

NPM package component gives an error if reexported in another library

I have a component library and one of our components uses react-toggle library. When I try to use our component in another app I get the error Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. I am using rollup as a bundler, here's the configuration.
import path from 'path';
import babel from '#rollup/plugin-babel';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import image from '#rollup/plugin-image';
import filesize from 'rollup-plugin-filesize';
import localResolve from 'rollup-plugin-local-resolve';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy';
import pkg from './package.json';
const SOURCE_DIR = path.resolve(__dirname, 'src');
const INPUT_FILE_PATH = `${SOURCE_DIR}/index.ts`;
const OUTPUT_NAME = 'InPlayerUI';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
const GLOBALS = {
react: 'React',
'react-dom': 'ReactDOM',
'styled-components': 'styled-components',
};
const PLUGINS = [
image(),
resolve({
mainFields: ['module', 'main', 'jsnext:main', 'browser'],
extensions,
}),
commonjs({ include: ['node_modules/**'] }),
babel({
include: ['src/**/*'],
exclude: 'node_modules/**',
babelHelpers: 'bundled',
extensions,
}),
localResolve(),
terser(),
filesize(),
copy({
targets: [{ src: './index.d.ts', dest: 'dist' }],
}),
];
const EXTERNAL = ['react', 'react-dom', 'styled-components'];
const OUTPUT_DATA = [
{
file: pkg.browser,
format: 'umd',
},
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'es',
},
];
const config = OUTPUT_DATA.map(({ file, format }) => ({
input: INPUT_FILE_PATH,
output: {
file,
format,
name: OUTPUT_NAME,
globals: GLOBALS,
},
external: EXTERNAL,
plugins: PLUGINS,
}));
export default config;
and the package.json
{
"name": "#inplayer-org/inplayer-ui",
"sideEffects": false,
"version": "2.0.4",
"author": "InPlayer",
"description": "InPlayer React UI Components",
"main": "dist/inplayer-ui.cjs.js",
"module": "dist/inplayer-ui.esm.js",
"browser": "dist/inplayer-ui.umd.js",
"jsnext:main": "dist/inplayer-ui.esm.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/inplayer-org/inplayer-ui"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/inplayer-org/inplayer-ui/issues"
},
"homepage": "https://github.com/inplayer-org/inplayer-ui#readme",
"scripts": {
"start": "yarn run storybook",
"storybook": "start-storybook -p 3001",
"build:storybook": "build-storybook -c .storybook -o docs",
"clean:dist": "rimraf ./dist",
"build": "yarn run clean:dist && npx rollup -c",
"lint": "eslint '*/**/*.{js,ts,tsx}' --quiet --fix",
"lint:watch": "esw -w src/**",
"prepublishOnly": "yarn build",
"lint:style": "stylelint -- \"./src/**/*.js\""
},
"dependencies": {
"react-toggle": "^4.1.1"
},
"peerDependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"styled-components": "^5.1.1"
},
"devDependencies": {
"#babel/cli": "^7.10.5",
"#babel/core": "^7.10.5",
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-private-methods": "^7.10.4",
"#babel/plugin-transform-classes": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"#rollup/plugin-babel": "^5.1.0",
"#rollup/plugin-commonjs": "^14.0.0",
"#rollup/plugin-image": "^2.0.5",
"#rollup/plugin-node-resolve": "^8.4.0",
"#storybook/addon-docs": "^5.3.19",
"#storybook/addon-info": "^5.3.19",
"#storybook/addon-knobs": "^5.3.19",
"#storybook/react": "^5.3.19",
"#types/dompurify": "^2.0.2",
"#types/lodash": "^4.14.157",
"#types/react": "^16.9.43",
"#types/react-dates": "^17.1.13",
"#types/react-dom": "^16.9.8",
"#types/react-toggle": "^4.0.2",
"#types/styled-components": "^5.1.1",
"#typescript-eslint/eslint-plugin": "3.7.0",
"#typescript-eslint/parser": "3.7.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.1.0",
"dompurify": "^2.0.12",
"eslint": "^7.5.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-config-react-app": "^5.2.1",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-react-hooks": "^4.0.8",
"eslint-watch": "^7.0.0",
"html-react-parser": "^0.13.0",
"lodash-es": "^4.17.15",
"moment": "^2.27.0",
"polished": "^3.6.5",
"prettier": "^2.0.5",
"rc-progress": "^3.0.0",
"react": "^16.13.1",
"react-addons-shallow-compare": "^15.6.2",
"react-dates": "^21.8.0",
"react-dom": "^16.13.1",
"react-icons": "^3.10.0",
"react-paginate": "^6.3.2",
"rimraf": "^3.0.2",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-filesize": "^9.0.2",
"rollup-plugin-local-resolve": "^1.0.7",
"rollup-plugin-terser": "^6.1.0",
"styled-components": "^5.1.1",
"styled-components-modifiers": "^1.2.5",
"styled-tools": "^1.7.2",
"stylelint": "^13.6.1",
"stylelint-config-standard": "^20.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.10.0",
"typescript": "^3.9.7"
}
}
This is the component
import React, { ChangeEvent } from 'react';
import styled from 'styled-components';
import Toggle from 'react-toggle';
import SwitchWrapper from './SwitchWrapper';
import Label from '../Label';
type SwitchProps = {
/**
* Whether the switch is checked or not
*/
checked: boolean;
/**
* Disable switch
*/
disabled?: boolean;
/**
* Id
*/
id: string;
/**
* Switch label
*/
label: string;
/**
* Function executed when the switch value changes
*/
onChange: (checked: boolean) => void;
};
const MarginLeftLabel = styled(Label)`
margin-right: 0.5rem;
`;
const Switch = ({ id, checked, label, disabled = false, onChange }: SwitchProps) => {
const onToggleChange = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target) {
onChange(e.target.checked);
}
};
return (
<SwitchWrapper>
<MarginLeftLabel disabled={disabled} htmlFor={id}>
{label}
</MarginLeftLabel>
<Toggle
id={id}
disabled={disabled}
checked={checked}
onChange={onToggleChange}
icons={false}
/>
</SwitchWrapper>
);
};
export default Switch;
I have seen some suggestions that the import could be wrong but I've made sure it isn't and if I use react-toggle directly in another app it works.
Note: I've tried using different npm packages and reexport components from them, it works fine, so I suppose it has something to do with react-toggle itself.

Storybook Viewport Addon: Custom Viewports Do Not Build (react)

I built an app using create-react-app. I create custom viewport types to add to my storybook. When I use yarn start everything builds fine and works. But when I build the app the viewports that I globally defined my preview.js file are not loading on the build. It is still the defaults. And for the life of me I can't figure out why. As far as I can tell I set it up the way the documentation explains.
This is my preview.js file
import { configure, addDecorator, addParameters } from '#storybook/react';
import { DocsPage, DocsContainer } from '#storybook/addon-docs/blocks';
import { withA11y } from '#storybook/addon-a11y';
import { GlobalStyle } from '../src/styles/global-styles';
const loaderFn = () => {
const allExports = [];
const styles = require.context('../src/styles', true, /\.stories\.(js|mdx)$/);
const req = require.context('../src/components', true, /\.stories\.(js|mdx)$/);
addDecorator(withA11y, GlobalStyle);
styles.keys().forEach(fname => allExports.push(styles(fname)));
req.keys().forEach(fname => allExports.push(req(fname)));
return allExports;
};
const customViewports = {
phoneSmall: {
name: 'Phone (320px min width)',
styles: {
width: '320px',
height: '667px',
},
},
tabletSmall: {
name: 'Tablet Small & Portrait (600px min width)',
styles: {
width: '600px',
height: '801px',
},
},
tabletLarge: {
name: 'Tablet Large & Landscape (960px min width)',
styles: {
width: '960px',
height: '768px',
},
},
desktop: {
name: 'Desktop (1200px min width)',
styles: {
width: '1200px',
height: '1024px',
},
},
};
configure(loaderFn, module);
addParameters({
docs: {
container: DocsContainer,
page: DocsPage,
},
viewport: { viewports: customViewports },
});
My main.js file
module.exports = {
stories: ['../src/**/*.stories.(js|mdx)'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-knobs/',
'#storybook/addon-actions',
'#storybook/addon-links',
'#storybook/addon-notes',
'#storybook/addon-storysource',
'#storybook/addon-a11y',
'#storybook/addon-docs',
'#storybook/addon-viewport',
]
}
Package.json
{
"name": "tamman-ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"#storybook/addon-a11y": "^5.3.17",
"#storybook/addon-actions": "^5.3.17",
"#storybook/addon-docs": "^5.3.17",
"#storybook/addon-knobs": "^5.3.17",
"#storybook/addon-links": "^5.3.17",
"#storybook/addon-notes": "^5.3.17",
"#storybook/addon-storyshots-puppeteer": "^5.3.17",
"#storybook/addon-storysource": "^5.3.17",
"#storybook/addon-viewport": "^5.3.17",
"#storybook/addons": "^5.3.17",
"#storybook/preset-create-react-app": "^2.1.0",
"#storybook/react": "^5.3.17",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"autoprefixer": "^9.7.5",
"camel-case": "^4.1.1",
"core-js": "^3.6.4",
"del": "^5.1.0",
"fs": "^0.0.1-security",
"node-sass": "^4.13.1",
"pascal-case": "^3.1.1",
"path": "^0.12.7",
"prop-types": "^15.7.2",
"puppeteer": "^2.1.1",
"react": "^16.12.0",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1",
"styled-components": "^5.0.1",
"xml2js": "^0.4.23"
},
"scripts": {
"start": "node ./src/components/atoms/Icon/utils/generate-icons.js && react-scripts start",
"build-page": "node ./src/components/atoms/Icon/utils/generate-icons.js && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"storybook": "start-storybook -p 9009 -s public",
"build": "yarn build-page && build-storybook -o build/storybook"
},
"eslintConfig": {
"extends": "react-app"
},
"homepage": ".",
"browserslist": [
"since 2010"
],
"devDependencies": {
"babel-loader": "^8.1.0",
"react-is": "^16.12.0"
}
}
Seems to be working fine. Try registering the viewport add-on
// main.js
module.exports = {
...
addons: [
...
'#storybook/addon-viewport/register',
],
]
}
Like the docs suggest.

React: Typescript or Babel error - You may need an appropriate loader to handle this file type

I have a custom hook and it works great! However, I'm getting Typescript errors if I simply use React.useState and React.useEffect. To fix this, I import in React and use (React as any).useState and (React as any).useEffect and then I get the following error that doesn't let me compile.
Hook:
import * as React from 'react';
import imageApi from 'xcel-api-generator/dist/image';
export const useUserProfileImage = (size, userProfileImage) => {
const [userImage, setUserImage] = (React as any).useState(null);
(React as any).useEffect(() => {
const runEffect = async () => {
const userImageCall = await imageApi.getTypeByImageType( {"imageType": size} )
setUserImage(userImageCall.url);
};
runEffect();
}, [userProfileImage])
return [userImage]
}
Error:
../rsv8-components/src/hooks/userProfileImage.ts 5:43
Module parse failed: Unexpected token (5:43)
You may need an appropriate loader to handle this file type.
|
| export const useUserProfileImage = (size, userProfileImage) => {
> const [userImage, setUserImage] = (React as any).useState(null);
| (React as any).useEffect(() => {
| const runEffect = async () => {
I'm totally clueless when it comes to webpack/babel etc... Could someone help guide me through this! Thanks!
Here is my local package.json file:
{
"name": "rsv8-components",
"version": "0.3.11",
"main": "./dist/module.js",
"types": "./dist/module.d.ts",
"dependencies": {
"#types/react-avatar-editor": "^10.3.5",
"react-avatar-editor": "^12.0.0-beta.0",
"react-scroll-to": "^1.2.2",
"react-slick": "^0.23.1",
"react-slick-deux": "https://github.com/aboorde/react-slick-deux#master",
"slick-carousel": "^1.8.1",
"tslib": "^1.9.3",
"xcel-observer": "*"
},
"peerDependencies": {
"react": "^16.8.0",
"react-bootstrap": "0.32.1",
"react-dom": "^16.8.0",
"react-fontawesome": "^1.6.1",
"react-router-dom": "^4.2.2",
"react-toastify": "^4.1.0",
"recompose": "^0.28.1",
"styled-components": "^2.4.0",
"xcel-asset-service": "*",
"xcel-react-animations": "*",
"xcel-react-core": "*",
"xcel-redux-orm": "*",
"xcel-util": "*"
},
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"fix-me-test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject",
"dist": "tsc --declaration",
"dist:watch": "tsc --declaration --watch",
"storybook": "start-storybook -p 6006 -c .storybook"
},
"devDependencies": {
"//": "peerDependencies",
"#storybook/addon-actions": "^4.0.0",
"#storybook/addon-knobs": "^4.0.0",
"#storybook/react": "^4.0.0",
"#types/jest": "^22.2.3",
"#types/node": "^8.9.1",
"#types/react": "^16.3.16",
"#types/react-dom": "^16.0.4",
"#types/react-router-dom": "^4.2.3",
"awesome-typescript-loader": "^3.4.1",
"enzyme-adapter-react-16": "^1.1.0",
"jest": "^23.6.0",
"jest-cli": "^23.4.1",
"jest-styled-components": "4.9.0",
"react": "^16.8.0",
"react-bootstrap": "0.32.1",
"react-dom": "^16.8.0",
"react-fontawesome": "^1.6.1",
"react-router-dom": "^4.2.2",
"react-scripts-ts": "^3.1.0",
"react-toastify": "^4.1.0",
"recompose": "^0.28.1",
"styled-components": "^2.4.0",
"ts-jest": "^22.4.2",
"ts-node": "^5.0.1",
"typescript": "^2.9.0",
"xcel-asset-service": "*",
"xcel-react-animations": "*",
"xcel-react-core": "*",
"xcel-redux-orm": "*",
"xcel-util": "*"
},
"jest": {
"coverageReporters": [
"lcov",
"cobertura",
"text-summary"
],
"testEnvironment": "jsdom",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testMatch": [
"<rootDir>/src/**/*.test.(ts|tsx)"
],
"collectCoverageFrom": [
"<rootDir>/src/**/*.(ts|tsx)",
"!<rootDir>/src/**/*.test.(ts|tsx)"
],
"transform": {
"\\.(ts|tsx)$": "ts-jest"
}
},
"publishConfig": {
"registry": "Blah blah removed"
}
}

Resources