Gathering detailed insights and metrics for @johnny___nia/react-imported-component
Gathering detailed insights and metrics for @johnny___nia/react-imported-component
npm install @johnny___nia/react-imported-component
Typescript
Module System
Node Version
NPM Version
70.2
Supply Chain
99.4
Quality
74.6
Maintenance
100
Vulnerability
100
License
TypeScript (94.02%)
JavaScript (5.81%)
HTML (0.17%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
645
Last Day
2
Last Week
3
Last Month
14
Last Year
65
666 Stars
466 Commits
40 Forks
12 Watching
585 Branches
14 Contributors
Minified
Minified + Gzipped
Latest Version
5.5.1
Package Id
@johnny___nia/react-imported-component@5.5.1
Unpacked Size
350.14 kB
Size
172.49 kB
File Count
23
NPM Version
6.5.0
Node Version
11.6.0
Cumulative downloads
Total Downloads
Last day
0%
2
Compared to previous day
Last week
50%
3
Compared to previous week
Last month
366.7%
14
Compared to previous month
Last year
-52.9%
65
Compared to previous year
4
1
29
Formerly - simple, but usable Async Component loader to be used with React-Hot-Loader.
Easy, universal, and could provide top results without any extra configuration.
Deliver a better experience with a single import.
Key features:
1import importedComponent from 'react-imported-component'; 2const Component = importedComponent( () => import('./Component')); 3 4const Component = importedComponent( () => import('./Component'), { 5 LoadingComponent: Spinner, 6 ErrorComponent: FatalError 7}); 8 9Component.preload(); // force preload 10 11// render it 12<Component... /> 13 14// 15import {lazy} from 'react-imported-component' 16const Component = lazy( () => import('./Component')); 17 18<Suspense> 19 <Component /> 20</Suspense>
Example: React.lazy vs Imported-component
importedComponent(importFunction, [options]): ComponentLoader
- main API, default export, HOC to create imported component.
not default
export from a importFunction
importedComponent.preload
- static method to preload components.
lazy
- helper to mimic React.lazy behavior (it is just _importedComponent_(fn, { async: true })
).
ComponentLoader
, the React Component variant of importedComponent. accepts importFunction
as a loadable
prop.
printDrainHydrateMarks()
, print our the drainHydrateMarks
.drainHydrateMarks()
, returns the currently used marks, and clears the list.whenComponentsReady():Promise
, will be resolved, when all components are loaded. Usually on the next "Promise" tick.rehydrateMarks():Promise
, loads marked async chunks.
whenComponentsReady():Promise
, will be resolved, when all marks are loaded.
dryRender(renderFunction):Promise
, perform sandboxed render, and resolves "whenComponentsReady".
There is no build in timeouts to display Error or Loading states. You could control everything by yourself
suspence
:P.One of the key features - "could work with any import statement, passed from anywhere".
All others full-cream
SSR bundlers relay on import
statement inside their HOC,
like in the example just above, disallowing any composition.
React-imported-component is different. But still "full-cream".
1import importedComponent from 'react-imported-component'; 2const myImportFunction = () => import('./Component') 3const Component = importedComponent(myImportFunction);
1import importedComponent from 'react-imported-component'; 2const mySuperImportedFactory = importFunction => importedComponent(importFunction); 3export default mySuperImportedFactory 4//... in another file 5mySuperImportedFactory(() => import('./Component')); 6mySuperImportedFactory(async () => { 7 const Component = await import('./Component'); 8 return () => <Component props /> 9});
If you need something complex, load more that one source for example.
1importedComponent(async () => { 2 const [Component1, Component2, i18n] = await Promise.all([ 3 import('./Component1'), 4 import('./Component2'), 5 import('./i18n') 6 ]); 7 return (props) => <Component1><Component2 i18n={i18n} {...props} /></Component1>; 8});
!!BUT NOT!!
1import importedComponent from 'react-imported-component'; 2const myImportFunction = () => import('./Component') 3const myAnotherFunction = () => myImportFunction; 4const Component = importedComponent(myAnotherFunction);
Function with import inside
should be passed directly to importedComponent,
as long importedComponent will analyze content of passed function.
To use webpack chunks - just add comments inside an import function
1importedComponent( () => import(/* webpackChunkName:'pages' */'./Component'));
That is all. Component will be loaded in time and then displayed. And updated on module replacement of course.
As long importedComponent
is a fabric function, which will produce React Component, which will perform the loading,
you may use React Component without calling fabric function.
1import {ComponentLoader} from 'react-imported-component'; 2 3const MyPage = () => ( 4 <ComponentLoader 5 loadable={() => import('./Page.js')} 6 // all fields are optional, and matches the same field of importedComponent. 7 LoadingComponent={Loading} 8 ErrorComponent={Error} 9 onError 10 11 exportPicker 12 render 13 async 14 /> 15);
Actually loadable
awaits for loadableResource
, but could do auto transformation.
1import {loadableResource} from 'react-imported-component'; 2loadable = {loadableResource(() => import('xxx'))}
loadableResource is just a sugar around import
.
Just pass down an option for importedComponent
, or prop for `ComponentLoader, and
catch the loading promise, imported component will throw if loading state will took a place.
It was usually a headache - async components and SSR, which is currently sync. React-imported-component break this cycle, making ServerSide rendering sync, and providing comprehensive ways to rehydrate rendered tree on client. It will detect server-side environment and precache all used components.
To enable full cream SSR follow these steps.
1{ 2 "plugins": ["react-imported-component/babel", "babel-plugin-dynamic-import-node"] 3}
On the client:
1{ 2 "plugins": ["react-imported-component/babel"] 3}
Imported-Component will hook into dynamic imports, providing extra information about files you want to load.
imported-components [sources ROOT] [targetFile]
(use .ts for TypeScript)1 "generate-imported-component": "imported-components src src/imported.js"
That's how the magic, bundle independent bundling works.
1import importedComponents from 'src/imported';
1 import { printDrainHydrateMarks, drainHydrateMarks } from 'react-imported-component'; 2 // this action will drain all currently used(by any reason) marks 3 // AND print a script tag 4 const html = renderToString(<YourApp />) + printDrainHydrateMarks(); 5 6 // OR return list of usedmarks, and yet again CLEAR the marks list. 7 const html = renderToString(<YourApp />) + "<script>const marks="+JSON.stringify(drainHydrateMarks())+"</script>";
! The current version expects you to synchronously render the application, and "drain" used
marks
. "Drain" will return used marks, and empty the state, making the application ready for the next render.
1 import { rehydrateMarks } from 'react-imported-component'; 2 3 // this will trigger all marked imports, and await for competition. 4 rehydrateMarks().then(() => { 5 // better 6 ReactDOM.hydrate(<App />,document.getElementById('main')); 7 // or 8 ReactDOM.render(<App />,document.getElementById('main')); 9 });
In case you have more than one rendering thread, for example in case of react-bootstrapper, ReactDOM.renderToStream or suspense, default approach will not work. You need one more component, to separate components my "rendering streams".
1import {ImportedStream, drainHydrateMarks} from 'react-imported-component'; 2 3// assuming res === express response 4function renderApplication(res) { 5 let streamUID = 0; 6 // ImportedStream is a async rendering "provider" 7 const stream = renderToStream( 8 <ImportedStream takeUID={uid => streamUID=uid}> 9 <YourApp /> 10 </ImportedStream>); 11 12 // you'd then pipe the stream into the response object until it's done 13 stream.pipe( 14 res, 15 { end: false }, 16 ) 17 18 // and finalize the response with closing HTML 19 stream.on('end', () => 20 // print marks used in the file 21 res.end(`${printDrainHydrateMarks(streamUID)}</body></html>`), 22 ) 23}
Use ImportedStream
to bound all imported component to one "streamId", and then - get used components.
Without ImportedStream
streamId will be just 0 for all renders. With ImportedStream
- it is a counter.
In case you could not use babel plugin, you could use "dryRender" API
1 import {dryRender} from 'react-imported-component';
2
3 // extract your rendering function
4 const renderApplication = (targetElement) => {
5 ReactDOM.render(<App />, targetElement);
6 }
7
8 // create invisible offscreen element
9 const invisibleElement = document.createElement('div');
10
11 dryRender(
12 // render Application to offscreen
13 () => renderApplication(invisibleElement)
14 // await all components to be loaded
15 )
16 // unmount useless Application
17 .then(() => unmountComponentAtNode(invisibleElement))
18 // render and rehydrate the real application
19 // better rehydrate
20 .then(() => renderApplication(document.getElementById('realElement')))
dryRender will render application offscreen, await for all parts to be loaded, and then resolve the promise. It is super-not-fast, and you will literally re-render everything twice, but it works (almost the same approach as react-async-component has).
You might not need to wait for all the chunks to be loaded before you can render you app - just use react-prerendered-component.
1import imported from 'react-imported-component'; 2import {PrerenderedComponent} from "react-prerendered-component"; 3 4const AsyncComponent = imported(() => import('./myComponent.js')); 5 6<PrerenderedComponent 7 // component will "go live" when chunk loading would be done 8 live={AsyncComponent.preload()} 9> 10 // until component is not "live" prerendered HTML code would be used 11 // that's why you need to `preload` 12 <AsyncComponent/> 13</PrerenderedComponent> 14
React.lazy
lazy
helper).Note 1: "RHL friendly" means that "loader" works with React-Hot-Loader out of the box. In other case you will have to wrap async chunk's export with
hot
function, provided by Hot-Loader.
Note 2: "no wave reduction" means - loader is produce several loading "waves"
Let's imagine complex case - index.js will async-load 2 chunks, and they also will load 2 async chunks. SSR will result 6 marks, but only 2 of them will be resolved and executed on startup, as long the nested async calls are described in the async chunks, which are not loaded yet. Thus will result a two(or more) "waves" of loading.
First you load files you can load(have imports to load them), next, a new code will start next "wave".
In 99.9% cases you will have only one "wave", and could loader reduce "waves" or not - does not matter. But in complex cases, you can have a lot of nested async chunks - then better to use loader which could handle it.
Very opinionated library. No loader have to support it, as long this is altering the whole dev process and could not be repeated in production. Read this article about pros and cons using react-hot-loader among your project.
There is no "best" or "worst" loader. They all almost similar on front-end and could solve most SSR specific tasks. They are all litteraly is a ONE command, just API a bit differs.
You are free to pick any. Or found your own one.
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/22 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
148 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More