single-spa-react | Single-spa lifecycles helper for React applications | Single Page Application library
kandi X-RAY | single-spa-react Summary
Support
Quality
Security
License
Reuse
- Returns an element s element to the given props .
- Creates a single SpaBound error .
- Mounts dom element .
- Render a React DOM element .
- render an element to the render callback
- Initialize a single component root component .
- Validate that React components are stable .
- Unmounts the rendered component
- creates a single SpaError
- Load root component .
single-spa-react Key Features
single-spa-react Examples and Code Snippets
Trending Discussions on single-spa-react
Trending Discussions on single-spa-react
QUESTION
I am trying to run test for my react application in which I used @ import such as
import { something } from "@atoms";
I did the mapping in the tsconfig.json file and it s used correctly when I run the application (command: "webpack serve --port 9004") but when I try to test (command "cross-env BABEL_ENV=test jest") the imports fails with this error:
Configuration error:
Could not locate module @atoms mapped as:
[
"src/components/atoms/index"
].
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/@atoms/": "[
"src/components/atoms/index"
]"
},
"resolver": undefined
}
1 | import { ReactElement } from "react";
2 |
> 3 | import { Something } from "@atoms";
| ^
4 |
5 |
6 | export const SomethingElse = ({
at createNoMappedModuleFoundError (../node_modules/jest-resolve/build/resolver.js:579:17)
at Object. (components/molecules/SomethingElse/index.tsx:3:1)
jest.config.js:
const { compilerOptions } = require("./tsconfig.json");
module.exports = {
rootDir: "src",
testEnvironment: "jsdom",
transform: {
"^.+\\.(j|t)sx?$": "babel-jest",
},
moduleNameMapper: {
"\\.(sass)$": "identity-obj-proxy",
"single-spa-react/parcel": "single-spa-react/lib/cjs/parcel.cjs",
...compilerOptions.paths,
},
setupFilesAfterEnv: ["@testing-library/jest-dom"],
};
tsconfig.json:
{
"extends": "ts-config-single-spa",
"compilerOptions": {
"jsx": "react-jsx",
"target": "ES5",
"baseUrl": ".",
"paths": {
"@app/*": ["src/*"],
"@configs/*": ["src/configs/*"],
"@configs": ["src/configs/index"],
"@components/*": ["src/components/*"],
"@components": ["src/components/index"],
"@constants/*": ["src/constants/*"],
"@constants": ["src/constants/index"],
"@enums/*": ["src/enums/*"],
"@enums": ["src/enums/index"],
"@hooks/*": ["src/hooks/*"],
"@hooks": ["src/hooks/index"],
"@services/*": ["src/services/*"],
"@services": ["src/services/index"],
"@store/*": ["src/store/*"],
"@store": ["src/store/index"],
"@themes/*": ["src/themes/*"],
"@themes": ["src/themes/index"],
"@utils/*": ["src/utils/*"],
"@utils": ["src/utils/index"],
"@types/*": ["src/types/*"],
"@types": ["src/types/index"],
"@assets/*": ["public/assets/*"],
"@atoms": ["src/components/atoms/index"],
"@molecules": ["src/components/molecules/index"],
"@organisms": ["src/components/organisms/index"],
"@pages": ["src/components/organisms/pages/index"]
}
},
"files": ["src/main-file.tsx"],
"include": ["src/**/*"]
}
ANSWER
Answered 2022-Apr-04 at 17:37I use the tsconfig-paths-jest npm package to add this to use the pathing from the tsconfig.json.
To add it into my Jest setup, I have this in the jest configuration script file (.js)
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);
module.exports = {
moduleNameMapper,
...
};
QUESTION
After upgrading react-scripts to v5, craco start
does not work properly. App starts with no error but in browser, there is a blank page and if i open inspector, i only see index.html codes not react codes. It was working well with react-scripts@4.0.3. Here is my local files;
package.json
{
"name": "test-app",
"private": true,
"version": "0.1.0",
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"dependencies": {
...
"@babel/preset-react": "^7.16.7",
...
"@craco/craco": "^6.4.3",
...
"babel-loader": "^8.2.3",
...
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "^5.0.0",
"scriptjs": "^2.5.9",
"single-spa": "^5.9.0",
"single-spa-react": "^4.6.1",
},
"devDependencies": {
"@babel/core": "7.7.2",
"@babel/plugin-proposal-class-properties": "^7.12.1",
"@babel/plugin-proposal-decorators": "^7.17.2",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.12.1",
"@babel/plugin-proposal-optional-chaining": "^7.6.0",
"@svgr/webpack": "6.2.1",
"@types/chance": "^1.0.8",
"@types/jest": "^24.9.0",
"@types/node": "^16.7.10",
"@types/react": "^16.9.18",
"@types/react-dom": "^16.9.5",
"@types/react-router-dom": "^5.1.3",
"@types/yargs": "^17.0.2",
"@typescript-eslint/eslint-plugin": "^4.14.1",
"@typescript-eslint/parser": "^4.14.1",
"@webpack-cli/serve": "^1.6.1",
"compression-webpack-plugin": "^9.2.0",
"css-loader": "3.2.0",
"dotenv": "^10.0.0",
"dotenv-expand": "5.1.0",
"dotenv-webpack": "^7.1.0",
"env-path": "^1.0.7",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"eslint": "^7.11.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-config-airbnb-typescript": "^12.3.1",
"eslint-config-react-app": "^6.0.0",
"eslint-config-standard": "^14.1.0",
"eslint-config-standard-jsx": "^8.1.0",
"eslint-import-resolver-typescript": "^2.4.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-flowtype": "5.2.0",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.22.0",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-standard": "^4.0.1",
"file-loader": "4.2.0",
"react-app-rewired": "^2.2.1",
"react-svg-loader": "^3.0.3",
"react-test-renderer": "^16.11.0",
"sass-loader": "8.0.0",
"style-loader": "1.0.0",
"systemjs-webpack-interop": "^2.3.7",
"terser-webpack-plugin": "5.3.1",
"tsconfig-paths-webpack-plugin": "^3.5.1",
"url-loader": "2.2.0",
"webpack": "^5.69.1",
"webpack-cli": "^4.9.2",
"webpack-manifest-plugin": "4.1.1",
"workbox-webpack-plugin": "6.4.2",
"yargs": "^17.1.1"
},
"scripts": {
"version": "node scripts/version.js",
"solid": "node scripts/solid.js",
"start": "craco start",
"build": "craco build"
},
"typings": "./src"
}
craco.config.ts
export default {
mode: 'development',
babel: {
plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]],
},
eslint: {
enable: false,
},
webpack: {
configure: (webpackConfig) => {
// add this line
// use System
webpackConfig.output.libraryTarget = 'system';
delete webpackConfig.optimization;
webpackConfig.externals = [
'react',
'react-dom',
'single-spa',
'react-router',
'react-router-dom',
'@mf-experiences',
];
return webpackConfig;
},
},
// Adding Server
devServer: (devServerConfig) => {
devServerConfig.proxy = {
'@mf-experiences': {
target: 'path...',
secure: false,
changeOrigin: true,
},
};
return devServerConfig;
},
};
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/nullifier.scss';
import './styles/index.scss';
import './tracking/facebook.ts';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
const setRealVh = () => {
document.documentElement.style.setProperty(
'--vh',
`${window.innerHeight * 0.01}px`
);
};
window.addEventListener('resize', setRealVh);
document.documentElement.style.setProperty('--intensity', `${768 * 0.005}px`);
ReactDOM.render(, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
// serviceWorkerRegistration.register({
// onUpdate: (registration) => registration.waiting.postMessage({ type: 'SKIP_WAITING' }),
// });
serviceWorkerRegistration.unregister();
ANSWER
Answered 2022-Feb-23 at 10:05craco
's Github readme, states that it is supporting Create React App (CRA) 4.*
. By this statement, I'm assuming CRA 5
is not officially supported by craco
.
However, this repository utilizes both CRA 5
and craco
(but I have not verified that it is working). Use this repository to compare your setup (after verifying that the linked repositry is working), and try different settings/configs to see if you get further.
QUESTION
I have downloaded the npm i --save esri-loader @esri/react-arcgis but why is it i cant load the map? did i miss something?
import React from 'react';
import Map from '../../component/Map/Map.js'
const HomePage = () => {
return (
);
};
export default HomePage;
component/Map/Map.js
import React , {useRef,useEffect} from 'react';
import {loadModules} from "esri-loader";
function Map() {
const MapElement=useRef(null)
useEffect(()=>{
let view;
loadModules(["esri/views/MapView", "esri/WebMap"],{
css:true
}).then(([MapView, WebMap])=>{
const webmap= new WebMap({
basemap:'topo-vector'
})
view = new MapView({
map:webmap,
center:[],
zoom:8,
container:MapElement.current
})
})
return()=>{
if(!!view){
view.destroy()
view=null
}
}
})
return (
)
}
export default Map
the error i get
the reference i used for this https://www.youtube.com/watch?v=0RC1Xf_0UUk
package.json
{
"name": "@country/app", "private": true, "scripts": {
"start": "webpack serve",
"start:standalone": "webpack serve --port 9003 --env standalone",
"build": "concurrently yarn:build:*",
"build:webpack": "webpack --mode=production",
"analyze": "webpack --mode=production --env analyze",
"lint": "eslint src --ext js",
"format": "prettier --write .",
"check-format": "prettier --check .",
"test": "cross-env BABEL_ENV=test jest",
"watch-tests": "cross-env BABEL_ENV=test jest --watch",
"prepare": "husky install",
"coverage": "cross-env BABEL_ENV=test jest --coverage" }, "devDependencies": {
"@arcgis/webpack-plugin": "^4.20.0",
"@babel/core": "^7.15.0",
"@babel/eslint-parser": "^7.15.0",
"@babel/plugin-transform-runtime": "^7.15.0",
"@babel/preset-env": "^7.15.0",
"@babel/preset-react": "^7.14.5",
"@babel/runtime": "^7.15.3",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^12.0.0",
"babel-jest": "^27.0.6",
"concurrently": "^6.2.1",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-config-react-important-stuff": "^3.0.0",
"eslint-plugin-prettier": "^3.4.1",
"husky": "^7.0.4",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.4.3",
"jest-cli": "^27.4.3",
"prettier": "^2.3.2",
"pretty-quick": "^3.1.1",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0",
"webpack-config-single-spa-react": "^4.0.0",
"webpack-dev-server": "^4.0.0",
"webpack-merge": "^5.8.0" }, "dependencies": {
"@esri/react-arcgis": "^5.1.0",
"@material-ui/styles": "^4.11.4",
"@mui/styles": "^5.2.2",
"@reach/router": "^1.3.4",
"arcgis-js-api": "^4.21.2",
"esri-loader": "^3.3.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"single-spa-react": "^4.3.1" }, }
ANSWER
Answered 2022-Jan-04 at 16:36Sorry for not directly responding to your described error, but I would not use esri-loader with newer versions of ArcGIS for JavaScript API. Why not npm as ES modules which do not require a separate script loader?
This way you can do simple imports like this:
import WebMap from "@arcgis/core/WebMap";
Here are the initial setup instructions:
Finally, here is a sample react app from Esri using exactly that:
QUESTION
I already add this to my package.json dist/custom-elements/index.mjs": "dist/custom-elements/index.js why i am having this error (below). did i miss something?
{
"name": "@map/react-app",
"private": true,
"scripts": {
"start": "webpack serve",
"start:standalone": "webpack serve --port 9003 --env standalone",
"build": "concurrently yarn:build:*",
"build:webpack": "webpack --mode=production",
"analyze": "webpack --mode=production --env analyze",
"lint": "eslint src --ext js",
"format": "prettier --write .",
"check-format": "prettier --check .",
"test": "cross-env BABEL_ENV=test jest",
"watch-tests": "cross-env BABEL_ENV=test jest --watch",
"prepare": "husky install",
"coverage": "cross-env BABEL_ENV=test jest --coverage"
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@babel/eslint-parser": "^7.15.0",
"@babel/plugin-transform-runtime": "^7.15.0",
"@babel/preset-env": "^7.15.0",
"@babel/preset-react": "^7.14.5",
"@babel/runtime": "^7.15.3",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^12.0.0",
"babel-jest": "^27.0.6",
"concurrently": "^6.2.1",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-config-react-important-stuff": "^3.0.0",
"eslint-plugin-prettier": "^3.4.1",
"husky": "^7.0.4",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.0.6",
"jest-cli": "^27.0.6",
"prettier": "^2.3.2",
"pretty-quick": "^3.1.1",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0",
"webpack-config-single-spa-react": "^4.0.0",
"webpack-dev-server": "^4.0.0",
"webpack-merge": "^5.8.0"
},
"dependencies": {
"@arcgis/core": "^4.21.2",
"@material-ui/styles": "^4.11.4",
"@mui/styles": "^5.2.2",
"@reach/router": "^1.3.4",
"@stencil/core": "^2.11.0",
"browserify": "^17.0.0",
"dotenv": "^10.0.0",
"dotenv-webpack": "^7.0.3",
"path-browserify": "^1.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"single-spa-react": "^4.3.1",
"web-vitals": "^2.1.2"
},
"lint-staged": {
"*.{js,jsx}": "pretty-quick --staged && eslint --fix"
},
"browser": {
"dist/custom-elements/index.mjs": "dist/custom-elements/index.js" // I'll already add this to may package.json, why i am having this error?
}
}
error
ERROR in ./node_modules/@esri/calcite-components/dist/custom-elements/index.mjs 1:0-147
Module not found: Error: Can't resolve '@stencil/core/internal/client' in 'C:\Users\Ronald\Desktop\Map\app-react\node_modules@esri\calcite-components\dist\custom-elements' Did you mean 'index.js'? BREAKING CHANGE: The request '@stencil/core/internal/client' failed to resolve only because it was resolved as fully specified (probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '.mjs' file, or a '.js' file where the package.json contains '"type": "module"'). The extension in the request is mandatory for it to be fully specified. Add the extension to the request.
ANSWER
Answered 2021-Dec-06 at 23:44The best solutions on this is in your webpack.config.js add this code
module:{
rules:[
{
test: /\.m?js/,
resolve: {
fullySpecified: false
}
}
]
},
and removed the browser in your package.json
QUESTION
The question:
How (is it possible) to configure webpack (with single-spa), to take make some packages (projects) under a scope (@orginazation) externals and other internals (not external) ?
Project information:
We are building a single-spa application using webpack an uses Github npm registrer (and github actions). All the micro front-ends are projects in Github, and some of them are util/helper/provider projects, that is compiled as externals with webpack.
But some of them are meant to be compiled with the micro-frontend (must not be external)
It seems that when webpack sees one of the project under the organization scope as external, it set all package under that scope to external!
As we can see from the log the "CompilingTool" will also be compiled as external, event thought it should not.
The packages are set in the files as:
import auth from "@ORGANIZATION/auth" // <- Should be external
import compilingTool from "@ORGANIZATION/compilingTool" // <- Should NOT be external
It is possible to change the external within the single-spa configuration to something else like:
import compilingTool from "ORGANIZATION-Internal/compilingTool" // Not optimal!!
But this means that intelligence don't work anymore because its now not pointing at the actual package within the micro-frontend (which still is "@ORGANIZATION/compilingTool")
It would not be optimal the have to begin using prebuild tool like gulp, to make such a transformation. And we don't like to have to use different Github account to have different scopes.
So any help or ideas to make webpack understand that it should NOT make "@ORGANIZATION/compilingTool" package external is mush appriciated.
Already tried:
From the webpack documentation of externals it should be possible to use a validation function and/or subtract but both dont works for the scoped packages with the spa-setup.
Compile/dependency info:
The single-spa/webpack compiles to SystemJs
Webpack and single-spa packages:
- "single-spa": "^5.9.3"
- "single-spa-layout": "1.6.0"
- "webpack": "^5.48.0"
- "webpack-cli": "^4.7.2"
- "webpack-config-single-spa-ts": "^3.0.0"
- "webpack-dev-server": "4.0.0-rc.0"
- "webpack-merge": "^5.8.0"
webpack.config.js (Project specific has been replaced with dummy code!)
const { merge } = require("webpack-merge");
const singleSpaDefaults = require("webpack-config-single-spa-react-ts");
const { readFileSync } = require('fs')
const path = require('path')
const dotenv = require('dotenv').config( {
path: path.join(__dirname, '.env')
} );
module.exports = (webpackConfigEnv, argv) => {
const defaultConfig = singleSpaDefaults({
orgName: "ORGANIZATION",
projectName: "SOME-MICRO-FRONTEND",
webpackConfigEnv,
argv,
});
return merge(defaultConfig, {
// modify the webpack config however you'd like to by adding to this object
externals: [
"react",
"react-dom",
"@ORGANIZATION/auth", // <- This should be external
//"@ORGANIZATION/compilingTool" // <- This should NOT be external
],
devServer: {
port: 5400,
https: {
key: readFileSync( path.resolve(__dirname, path.join(process.env.CERT_PATH, process.env.CERT_KEY_FILE_NAME))),
cert: readFileSync(path.resolve(__dirname, path.join(process.env.CERT_PATH, process.env.CERT_FILE_NAME)))
}
},
});
};
Run time console output from webpack build: (Project specific has been replaced with dummy code!)
webpack serve
[webpack-dev-server] Project is running at:
[webpack-dev-server] Loopback: https://localhost:XXXX/
[webpack-dev-server] On Your Network (IPv4): https://XX.X.XXX.XXX:XXXX/
[webpack-dev-server] Content not from webpack is served from 'C:\path-to-PROJECT\public' directory
[webpack-dev-server] 404s will fallback to '/index.html' asset PROJECT-NAME.js 436 KiB [emitted] (name: main) 1 related asset asset index.html 3.1 KiB [emitted] runtime modules 26.3 KiB 14 modules modules by path ./node_modules/ 329 KiB 58 modules modules by path external "@ORGANIZATION/ 210 bytes external "@ORGANIZATION/auth" 42 bytes [built] [code generated] external "@ORGANIZATION/compilingTool" 42 bytes [built] [code generated] modules by path (...OTHER LOGS... ) external "react" 42 bytes [built] [code generated] external "react-dom" 42 bytes [built] [code generated] webpack 5.48.0 compiled successfully in 17732 ms No issues found.
ANSWER
Answered 2021-Aug-05 at 15:14This is possible by passing in orgPackagesAsExternal: false
to the single-spa webpack config, in your case named singleSpaDefaults
. Per the create-single-spa documentation,
This changes whether package names that start with @your-org-name are treated as webpack externals or not. Defaults to true.
You will then need to either:
- Enumerate which packages to mark as external
- Provide a function that does this (which you've noted in your question)
and then merge that with single-spa's config as usual. Because this can become verbose and annoying to do for every microfrontend, consider doing this in a base config that you publish that is specific for your company and which each mfe will then need to consume.
QUESTION
After converting a react app to single spa which had il8n implemented I am facing a problem where translation.json cannot be accessed hence not fetching the labels.
Should I modify something in the webpack.config.js to get it right
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import i18nextHttpBackend from "i18next-http-backend";
import Cookies from "js-cookie";
import LanguageDetector from "i18next-browser-languagedetector";
i18n
.use(i18nextHttpBackend)
.use(initReactI18next)
.use(LanguageDetector)
.init({
lng: Cookies.get("locale") || "es",
fallbackLng: "en",
debug: false,
supportedLngs: ["en", "es"],
interpolation: {
escapeValue: false,
},
});
export default i18n;
il8n is imported in App.js import "./i18n";
Initially before converting to single spa the app was working fine and making a call to http://localhost:3000/locales/en/translation.json but after converting the app to single spa the get request would fail. http://single-spa-playground.org/locales/en/translation.json
I did follow this tutorial https://www.youtube.com/watch?v=W8oaySHuj3Y&list=PLLUD8RtHvsAOhtHnyGx57EYXoaNsxGrTU&index=13 to convert the react app to single spa.
WebPack Config
const { merge } = require("webpack-merge");
const singleSpaDefaults = require("webpack-config-single-spa-react");
const Dotenv = require("dotenv-webpack");
module.exports = (webpackConfigEnv, argv) => {
console.log(webpackConfigEnv);
const defaultConfig = singleSpaDefaults({
orgName: "WHATEVR",
projectName: "WHATEVER",
webpackConfigEnv,
argv,
});
return merge(defaultConfig, {
// modify the webpack config however you'd like to by adding to this object
plugins: [new Dotenv()],
devServer: {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods":
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers":
"X-Requested-With, content-type, Authorization",
},
},
});
};
Tried Solution but still not solved Reactjs - error loading translation files
ANSWER
Answered 2021-May-24 at 14:03The issue is that previously, the React app also served as the server that provided the index.html file along with other static assets (eg. your localized translation json files). In single-spa, that is no longer the case; that is instead now the root-config. You'll need to update your i18next-http-backend loadPath
configuration so that the library tries to retrieve them from the right path which is no longer the root url. Without being familiar with what you want to achieve, you have two options:
- use
__webpack_public_path__
to dynamically create the correct URL to point to the assets served by this microfrontend, eg.loadPath: `${__webpack_public_path__} /locales/{{lng}}/{{ns}}.json`,
- if you have a separate i18n service, point the URL to that. This may also require
crossDomain
andwithCredentials
depending on how that is also configured.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install single-spa-react
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page