- Notifications
You must be signed in to change notification settings - Fork632
🔥 An extremely fast, React-like JavaScript library for building modern user interfaces
License
infernojs/inferno
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Inferno is an insanely fast, React-like library for building high-performance user interfaces on both the client and server.
The main objective of the InfernoJS project is to provide the fastest possibleruntime performance for web applications. Inferno excels at rendering real time data views or large DOM trees.
The performance is achieved through multiple optimizations, for example:
- Inferno's own JSX compilers creates monomorphic
createVNode
calls, instead ofcreateElement
calls.Optimizing runtime performance of the application.- SWC plugin inferno is a plugin forSWC. It can compile TSX and JSX
- Babel plugin inferno is a plugin forBabelJs. It can compile JSX.
- TS plugin inferno is a plugin forTSC. It can compile TSX.
- Inferno's diff process uses bitwise flags to memoize the shape of objects
- Child nodes are normalized only when needed
- Special JSX flags can be used during compile time to optimize runtime performance at application level
- Many micro optimizations
- Component driven + one-way data flow architecture
- React-like API, concepts and component lifecycle events
- Partial synthetic event system, normalizing events for better cross browser support
- Inferno's
linkEvent
feature removes the need to use arrow functions or binding event callbacks - Isomorphic rendering on both client and server with
inferno-server
- Unlike React and Preact, Inferno has lifecycle events on functional components
- Unlike Preact and other React-like libraries, Inferno has controlled components for input/select/textarea elements
- Components can be rendered outside their current html hierarchy using
createPortal
- API - Support forolder browsers without any polyfills
- defaultHooks for Functional components, this way re-defining lifecycle events per usage can be avoided
- Inferno supports setting styles using string
<div></div>
or using object literal syntax<div style={{"background-color": "red"}}></div>
. For camelCase syntax support seeinferno-compat
. - Fragments (v6)
- createRef and forwardRef APIs (v6)
- componentDidAppear, componentWillDisappear and componentWillMove (v8) - class and function component callbacks to ease animation work, seeinferno-animation package
Inferno v9 requires following features to be present in the executing runtime:
Promise
String.prototype.includes()
String.prototype.startsWith()
Array.prototype.includes()
Object.spread()
for ... of
Since version 4 we have started running our test suitewithout any polyfills.Inferno is now part ofSaucelabs open source program and we use their service for executing the tests.
InfernoJS is actively tested with browsers listed below, however it may run well on older browsers as well.This is due to limited support of browser versions in recent testing frameworks.https://github.com/jasmine/jasmine/blob/main/release_notes/5.0.0.md
Live examples athttps://infernojs.github.io/inferno
Let's start with some code. As you can see, Inferno intentionally keeps the same design ideas as React regarding components: one-way data flow and separation of concerns.
In these examples, JSX is used via theInferno JSX Babel Plugin to provide a simple way to express Inferno virtual DOM. You do not need to use JSX, it's completelyoptional, you can usehyperscript orcreateElement (like React does).Keep in mind that compile time optimizations are available only for JSX.
import{render}from'inferno';constmessage="Hello world";render(<MyComponentmessage={message}/>,document.getElementById("app"));
Furthermore, Inferno also uses ES6 components like React:
import{render,Component}from'inferno';classMyComponentextendsComponent{constructor(props){super(props);this.state={counter:0};}render(){return(<div><h1>Header!</h1><span>Counter is at:{this.state.counter}</span></div>);}}render(<MyComponent/>,document.getElementById("app"));
Because performance is an important aspect of this library, we want to show you how to optimize your application even further.In the example below we optimize diffing process by using JSX$HasVNodeChildren and$HasTextChildren to predefine children shape compile time.In the MyComponent render method there is a div that contains JSX expressionnode
as its content. Due to dynamic nature of Javascriptthat variablenode
could be anything and Inferno needs to go through the normalization process to make sure there are no nested arrays or other invalid data.Inferno offers a feature called ChildFlags for application developers to pre-define the shape of vNode's child node. In this example caseit is using$HasVNodeChildren
to tell the JSX compiler, that this vNode contains only single element or component vNode.Now inferno will not go into the normalization process runtime, but trusts the developer decision about the shape of the object and correctness of data.If this contract is not kept andnode
variable contains invalid value for the pre-defined shape (fe.null
), then application would crash runtime.There is also span-element in the same render method, which content is set dynamically through_getText()
method. There$HasTextChildren
child-flagfits nicely, because the content of that given "span" is never anything else than text.All the available child flags are documentedhere.
import{createTextVNode,render,Component}from'inferno';classMyComponentextendsComponent{constructor(props){super(props);this.state={counter:0};}_getText(){return'Hello!';}render(){constnode=this.state.counter>0 ?<div>0</div> :<span$HasTextChildren>{this._getText()}</span>;return(<div><h1>Header!</h1><div$HasVNodeChildren>{node}</div></div>);}}render(<MyComponent/>,document.getElementById("app"));
To tear down inferno application you need to render null on root element.Renderingnull
will trigger unmount lifecycle hooks for whole vDOM tree and remove global event listeners.It is important to unmount unused vNode trees to free browser memory.
import{createTextVNode,render,Component}from'inferno';constrootElement=document.getElementById("app");// Start the applicationrender(<ExampleComponent/>,rootElement);// Tear downrender(null,rootElement);
If you have built something using Inferno you can add them here:
- Simple Clock (@JSFiddle)
- Simple JS Counter (@github/scorsi): SSR Inferno (view) + Cerebral (state manager) + FuseBox (build system/bundler)
- Online interface to TMDb movie database (@codesandbox.io): Inferno +Inferno hyperscript (view) +Superagent (network requests) + Web component (custom elements v1) +state-transducer(state machine library)
- Lemmy - a self-hostable reddit alternative (front end in Inferno)
The easiest way to get started with Inferno is by usingCreate Inferno App.
Alternatively, you can try any of the following:
- theInferno Boilerplate for a very simple setup.
- for a more advanced example demonstrating how Inferno might be used, we recommend trying outInferno Starter Project bynightwolfz.
- for using Inferno to build a mobile app, tryInferno Mobile Starter Project byRudy-Zidan.
- forTypeScript support and bundling, check outts-plugin-inferno, orinferno-typescript-example.
- for an example of how to use Inferno incodesandbox:https://codesandbox.io/s/znmyj24w4p
- for usingparcel and typescript
Core package:
npm install --save inferno
Addons:
# server-side renderingnpm install --save inferno-server# routingnpm install --save inferno-router
Pre-bundled files for browser consumption can be found onour cdnjs:
Or on jsDelivr:
https://cdn.jsdelivr.net/npm/inferno@latest/dist/inferno.min.js
Or on unpkg.com:
https://unpkg.com/inferno@latest/dist/inferno.min.js
npm install --save-dev babel-plugin-inferno
npm install --save inferno-hyperscript
npm install --save inferno-create-element
npm install --save-dev inferno-compat
Note: Make sure you read more aboutinferno-compat
before using it.
Inferno now has bindings available for some of the major state management libraries out there:
- Redux via
inferno-redux
- MobX via
inferno-mobx
- Cerebral via
@cerebral/inferno
Inferno has its ownJSX Babel plugin.
- Inferno doesn't have a fully synthetic event system like React does. Inferno has a partially synthetic event system, instead opting to only delegate certain events (such as
onClick
). - Inferno doesn't support React Native. Inferno was only designed for the browser/server with the DOM in mind.
- Inferno doesn't support legacy string refs, use
createRef
or callbackref
API - Inferno provides lifecycle events on functional components. This is a major win for people who prefer lightweight components rather than ES2015 classes.
- Inferno has a partial synthetic event system, resulting in better performance via delegation of certain events.
- Inferno ismuch faster than Preact in rendering, updating and removing elements from the DOM. Inferno diffs against virtual DOM, rather than the real DOM (except when loading from server-side rendered content), which means it can make drastic improvements. Unfortunately, diffing against the real DOM has a 30-40% overhead cost in operations.
- Inferno fully supports controlled components for
input
/select
/textarea
elements. This prevents lots of edgecases where the virtual DOM is not the source of truth (it should always be). Preact pushes the source of truth to the DOM itself. - Inferno provides lifecycle events on functional components. This is a major win for people who prefer lightweight components rather than ES2015 classes.
Like React, Inferno also uses a light-weight synthetic event system in certain places (although both event systems differ massively). Inferno's event system provides highly efficient delegation and an event helper calledlinkEvent
.
One major difference between Inferno and React is that Inferno does not rename events or change how they work by default. Inferno only specifies that events should be camel cased, rather than lower case. Lower case events will bypassInferno's event system in favour of using the native event system supplied by the browser. For example, when detecting changes on an<input>
element, in React you'd useonChange
, with Inferno you'd useonInput
instead (thenative DOM event isoninput
).
Available synthetic events are:
onClick
onDblClick
onFocusIn
onFocusOut
onKeyDown
onKeyPress
onKeyUp
onMouseDown
onMouseMove
onMouseUp
onTouchEnd
onTouchMove
onTouchStart
linkEvent()
is a helper function that allows attachment ofprops
/state
/context
or other data to events without needing tobind()
them or use arrow functions/closures. This is extremely useful when dealing with events in functional components. Below is an example:
import{linkEvent}from'inferno';functionhandleClick(props,event){props.validateValue(event.target.value);}functionMyComponent(props){return<div><inputtype="text"onClick={linkEvent(props,handleClick)}/><div>;}
This is an example of using it with ES2015 classes:
import{linkEvent,Component}from'inferno';functionhandleClick(instance,event){instance.setState({data:event.target.value});}classMyComponentextendsComponent{render(){return<div><inputtype="text"onClick={linkEvent(this,handleClick)}/><div>;}}
linkEvent()
offers better performance than binding an event in a class constructor and using arrow functions, so use it where possible.
In HTML, form elements such as<input>
,<textarea>
, and<select>
typically maintain their own state and update it based on user input.In Inferno, mutable state is typically kept in the state property of components, and only updated withsetState()
.
We can combine the two by making the Inferno state be the "single source of truth". Then the Inferno component that renders a form alsocontrols what happens in that form on subsequent user input. An input form element whose value is controlled byInferno in this way is called a "controlled component".
import{render}from'inferno';render(<div/>,document.getElementById("app"));
Render a virtual node into the DOM in the supplied container given the supplied virtual DOM. If the virtual node was previously renderedinto the container, this will perform an update on it and only mutate the DOM as necessary, to reflect the latest Inferno virtual node.
Warning: If the container element is not empty before rendering, the content of the container will be overwritten on the initial render.
createRenderer
creates an alternative render function with a signature matching that of the first argument passed to a reduce/scan function. This allows for easier integration with reactive programming libraries, likeRxJS andMost.
import{createRenderer}from'inferno';import{scan,map}from'most';constrenderer=createRenderer();// NOTE: vNodes$ represents a stream of virtual DOM node updatesscan(renderer,document.getElementById("app"),vNodes$);
Seeinferno-most-fp-demo for an example of how to build an app architecture around this.
Creates an Inferno VNode using a similar API to that found with React'screateElement()
import{Component,render}from'inferno';import{createElement}from'inferno-create-element';classBasicComponentextendsComponent{render(){returncreateElement('div',{className:'basic'},createElement('span',{className:this.props.name},'The title is ',this.props.title))}}render(createElement(BasicComponent,{title:'abc'}),document.getElementById("app"));
Class component:
import{Component}from'inferno';classMyComponentextendsComponent{render(){return<div>My Component</div>}}
This is the base class for Inferno Components when they're defined using ES6 classes.
Functional component:
constMyComponent=({ name, age})=>(<span>My name is:{name} and my age is:{age}</span>);
Another way of using defaultHooks.
exportfunctionStatic(){return<div>1</div>;}Static.defaultHooks={onComponentShouldUpdate(){returnfalse;}};
Default props
exportfunctionMyFunctionalComponent({value}){return<div>{value}</div>;}MyFunctionalComponent.defaultProps={value:10};
Functional components are first-class functions where their first argument is theprops
passed through from their parent.
import{createVNode}from'inferno';createVNode(flags,type,[className],[...children],[childFlags],[props],[key],[ref])
createVNode is used to create html element's virtual node object. TypicallycreateElement()
(package:inferno-create-element
),h()
(package:inferno-hyperscript
) or JSX are used to createVNode
s for Inferno, but under the hood they all usecreateVNode()
. Below is an example ofcreateVNode
usage:
import{VNodeFlags,ChildFlags}from'inferno-vnode-flags';import{createVNode,createTextVNode,render}from'inferno';constvNode=createVNode(VNodeFlags.HtmlElement,'div','example',createTextVNode('Hello world!'),ChildFlags.HasVNodeChildren);// <div>Hello world!</div>render(vNode,container);
createVNode
arguments explained:
flags
: (number) is a value fromVNodeFlags
, this is a numerical value that tells Inferno what the VNode describes on the page.
type
: (string) is tagName for element for example 'div'
className
: (string) is the class attribute ( it is separated from props because it is the most commonly used property )
children
: (vNode[]|vNode) is one or array of vNodes to be added as children for this vNode
childFlags
: (number) is a value fromChildFlags
, this tells inferno shape of the children so normalization process can be skipped.
props
: (Object) is object containing all other properties. fe:{onClick: method, 'data-attribute': 'Hello Community!}
key
: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
ref
: (function) callback which is called when DOM node is added/removed from DOM.
import{createComponentVNode}from'inferno';createComponentVNode(flags,type,[props],[key],[ref])
createComponentVNode is used for creating vNode for Class/Functional Component.
Example:
import{VNodeFlags,ChildFlags}from'inferno-vnode-flags';import{createVNode,createTextVNode,createComponentVNode,render}from'inferno';functionMyComponent(props,context){returncreateVNode(VNodeFlags.HtmlElement,'div','example',createTextVNode(props.greeting),ChildFlags.HasVNodeChildren);}constvNode=createComponentVNode(VNodeFlags.ComponentFunction,MyComponent,{greeting:'Hello Community!'},null,{onComponentDidMount(){console.log("example of did mount hook!")}})// <div>Hello Community!</div>render(vNode,container);
createComponentVNode
arguments explained:
flags
: (number) is a value fromVNodeFlags
, this is a numerical value that tells Inferno what the VNode describes on the page.
type
: (Function/Class) is the class or function prototype for Component
props
: (Object) properties passed to Component, can be anything
key
: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
ref
: (Function|Object) this property is object for Functional Components defining all its lifecycle methods. For class Components this is function callback for ref.
createTextVNode is used for creating vNode for text nodes.
createTextVNode
arguments explained:text: (string) is a value for text node to be created.key: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
import{createTextVNode}from'inferno';createTextVNode(text,key)
This package has same API as React.cloneElement
import{cloneVNode}from'inferno-clone-vnode';cloneVNode(vNode,[props],[...children])
Clone and return a new InfernoVNode
using aVNode
as the starting point. The resultingVNode
will have the originalVNode
's props with the new props merged in shallowly. New children will replace existing children. key and ref from the originalVNode
will be preserved.
cloneVNode()
is almost equivalent to:
<VNode.type{...VNode.props}{...props}>{children}</VNode.type>
An example of usingcloneVNode
:
import{createVNode,render}from'inferno';import{cloneVNode}from'inferno-clone-vnode';import{VNodeFlags}from'inferno-vnode-flags';constvNode=createVNode(VNodeFlags.HtmlElement,'div','example','Hello world!');constnewVNode=cloneVNode(vNode,{id:'new'});// we are adding an id prop to the VNoderender(newVNode,container);
If you're using JSX:
import{render}from'inferno';import{cloneVNode}from'inferno-clone-vnode';constvNode=<divclassName="example">Hello world</div>;constnewVNode=cloneVNode(vNode,{id:'new'});// we are adding an id prop to the VNoderender(newVNode,container);
HTML:
<divid="root"></div><divid="outside"></div>
#"auto" data-snippet-clipboard-copy-content="const { render, Component, version, createPortal } from 'inferno';function Outsider(props) {return <div>{`Hello ${props.name}!`}</div>;}const outsideDiv = document.getElementById('outside');const rootDiv = document.getElementById('root');function App() {return ( <div> Main view ... {createPortal(<Outsider name="Inferno" />, outsideDiv)} </div> );}// render an instance of Clock into <body>:render(<App />, rootDiv);">
const{ render, Component, version, createPortal}from'inferno';functionOutsider(props){return<div>{`Hello${props.name}!`}</div>;}constoutsideDiv=document.getElementById('outside');constrootDiv=document.getElementById('root');functionApp(){return(<div> Main view ...{createPortal(<Outsidername="Inferno"/>,outsideDiv)}</div>);}// render an instance of Clock into <body>:render(<App/>,rootDiv);
Results into:
<divid="root"><div>Main view ...</div></div><divid="outside"><div>Hello Inferno!</div></div>
Cool, huh? Updates (props/context) will flow into "Outsider" component from the App component the same way as any other Component.For inspiration on how to use it clickhere!
createRef API provides shorter syntax than callback ref when timing of element is not needed.
import{Component,render,createRef}from'inferno';classFoobarextendsComponent{constructor(props){super(props);// Store reference somewherethis.element=createRef();// Returns object {current: null}}render(){return(<div><spanid="span"ref={this.element}> Ok</span></div>);}}render(<Foobar/>,container);
createFragment is the native way to createFragment vNode.createFragment(children: any, childFlags: ChildFlags, key?: string | number | null)
createFragment
arguments explained:
children
: (Array) Content of fragment vNode, typically array of VNodes
childFlags
: (number) is a value fromChildFlags
, this tells inferno shape of the children so normalization process can be skipped.
key
: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
Alternative ways to create fragment vNode are:
- Using JSX
<> ... </>
,<Fragment> .... </Fragment>
or<Inferno.Fragment> ... </Inferno.Fragment>
- Using createElement API
createElement(Inferno.Fragment, {key: 'test'}, ...children)
- Using hyperscript API
h(Inferno.Fragment, {key: 'test'}, children)
In the below example both fragments are identical except they have different key
import{Fragment,render,createFragment}from'inferno';import{ChildFlags}from'inferno-vnode-flags';functionFoobar() {return(<div$HasKeyedChildren>{createFragment([<div>Ok</div>,<span>1</span>],ChildFlags.HasNonKeyedChildren,'key1')}<Fragmentkey="key2"><div>Ok</div><span>1</span></Fragment></div>);}render(<Foobar/>,container);
forwardRef is a new mechanism to "forward" ref inside a functional Component.It can be useful if you have simple functional Components and you want to create reference to a specific element inside it.
import{forwardRef,Component,render}from'inferno';constFancyButton=forwardRef((props,ref)=>(<buttonref={ref}className="FancyButton">{props.children}</button>));classHelloextendsComponent{render(){return(<FancyButtonref={btn=>{if(btn){// btn variable is the button rendered from FancyButton}}}> Click me!</FancyButton>);}}render(<Hello/>,container);
import{hydrate}from'inferno-hydrate';hydrate(<div/>,document.getElementById("app"));
Same asrender()
, but is used to hydrate a container whose HTML contents were rendered byinferno-server
. Inferno will attempt to attach event listeners to the existing markup.
This feature has been moved from inferno to inferno-compat in v6. No options are needed anymore.
Note: we recommend using aref
callback on a component to find its instance, rather than usingfindDOMNode()
.findDOMNode()
cannot be used on functional components.
If a component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.In most cases, you can attach a ref to the DOM node and avoid usingfindDOMNode()
at all. When render returns null or false,findDOMNode()
returns null.If Component has rendered fragment it returns the first element.
VNodeFlags:
VNodeFlags.HtmlElement
VNodeFlags.ComponentUnknown
VNodeFlags.ComponentClass
VNodeFlags.ComponentFunction
VNodeFlags.Text
VNodeFlags.SvgElement
VNodeFlags.InputElement
VNodeFlags.TextareaElement
VNodeFlags.SelectElement
VNodeFlags.Portal
VNodeFlags.ReCreate
(JSX$ReCreate) always re-creates the vNodeVNodeFlags.ContentEditable
VNodeFlags.Fragment
VNodeFlags.InUse
VnodeFlags.ForwardRef
VNodeFlags.Normalized
VNodeFlags Masks:
VNodeFlags.ForwardRefComponent
Functional component wrapped in forward refVNodeFlags.FormElement
- Is form elementVNodeFlags.Element
- Is vNode elementVNodeFlags.Component
- Is vNode ComponentVNodeFlags.DOMRef
- Bit set when vNode holds DOM referenceVNodeFlags.InUseOrNormalized
- VNode is used somewhere else or came from normalization processVNodeFlags.ClearInUseNormalized
- Opposite mask of InUse or Normalized
ChildFlags
ChildFlags.UnknownChildren
needs NormalizationChildFlags.HasInvalidChildren
is invalid (null, undefined, false, true)ChildFlags.HasVNodeChildren
(JSX$HasVNodeChildren) is single vNode (Element/Component)ChildFlags.HasNonKeyedChildren
(JSX$HasNonKeyedChildren) is Array of vNodes non keyed (no nesting, no holes)ChildFlags.HasKeyedChildren
(JSX$HasKeyedChildren) is Array of vNodes keyed (no nesting, no holes)ChildFlags.HasTextChildren
(JSX$HasTextChildren) vNode contains only text
ChildFlags Masks
ChildFlags.MultipleChildren
Is Array
import{renderToString}from'inferno-server';conststring=renderToString(<div/>);
Render a virtual node into an HTML string, given the supplied virtual DOM.
Name | Triggered when | Arguments to callback |
---|---|---|
onComponentWillMount | a functional component is about to mount | |
onComponentDidMount | a functional component has mounted successfully | domNode |
onComponentShouldUpdate | a functional component has been triggered to update | lastProps, nextProps |
onComponentWillUpdate | a functional component is about to perform an update | lastProps, nextProps |
onComponentDidUpdate | a functional component has performed an update | lastProps, nextProps |
onComponentWillUnmount | a functional component is about to be unmounted | domNode |
onComponentDidAppear | a functional component has mounted and is ready for animations | domNode, props |
onComponentWillDisappear | a functional component is unmounted before DOM node is removed | domNode, props, callback |
onComponentWillDisappear has special type of argument "callback" which needs to be called when component is ready to be removed from the DOM. fe. after animations are finished.
All these Component lifecycle methods ( includingrender
andsetState - callback
) are called with Component instance context. You don't need to "bind" these methods.
Name | Triggered when | Arguments to callback |
---|---|---|
componentDidMount | component has been mounted successfully | |
componentWillMount | component is about to mount | |
componentWillReceiveProps | before render when component updates | nextProps, context |
shouldComponentUpdate | component has been triggered to update | nextProps, nextState |
componentWillUpdate | component is about to perform an update | nextProps, nextState, context |
componentDidUpdate | component has performed an update | lastProps, lastState, snapshot |
componentWillUnmount | component is about to be unmounted | |
getChildContext | before render method, return value object is combined to sub tree context | |
getSnapshotBeforeUpdate | before component updates, return value is sent to componentDidUpdate as 3rd parameter | lastProps, lastState |
static getDerivedStateFromProps | before render method | nextProps, state |
componentDidAppear | component has mounted and is ready for animations | domNode |
componentWillDisappear | component is unmounted before DOM node is removed | domNode, callback |
componentWillDisappear has special type of argument "callback" which needs to be called when component is ready to be removed from the DOM. fe. after animations are finished.
Functional lifecycle events must be explicitly assigned via props onto a functional component like shown below:
import{render}from'inferno';functionmounted(domNode){// [domNode] will be available for DOM nodes and components (if the component has mounted to the DOM)}functionFunctionalComponent({ props}){return<div>Hello world</div>;}render(<FunctionalComponentonComponentDidMount={mounted}/>,document.getElementById("app"));
Please note: class components (ES2015 classes) frominferno
do not support the same lifecycle events (they have their own lifecycle events that work as methods on the class itself).
By default, Inferno will run in development mode. Development mode provides extra checks and better error messages at the cost of slower performance and larger code to parse.When using Inferno in a production environment, it is highly recommended that you turn off development mode.
Ensure the environment variableprocess.env.NODE_ENV
is set toproduction
.
When building your application bundle, ensureprocess.env.NODE_ENV
is replaced with string"development"
or"production"
based on the workflow.It is recommended to usets-plugin-inferno for typescript TSX compilation andbabel-plugin-infeno for javascript JSX compilation.
When building for development, you may want to useinferno.dev.mjs
for v9 or newer andinferno.dev.esm.js
for older than v9. That bundle file contains ES6 exports for better tree-shaking support, improved error messages and added validation to help fixing possible issues during development.The file is found frompackage.json
-dev:module
entry point and the files are physically located innode_modules/inferno/dist/
folder.Remember that it is not recommended to use that file in production due to slower performance. For production usage usenode_modules/inferno/dist/inferno.mjs
-file for v9 or newer andnode_modules/inferno/dist/inferno.esm.js
-file for older than v9.
Example ofWebpack configuration:
constpath=require('path');constinfernoTsx=require('ts-plugin-inferno').default;...webpackconfig ... module:{rules:[{test:/\.js$/,// Add "jsx" if your application uses `jsx` file extensionsexclude:/node_modules/,use:[{loader:'babel-loader',options:{plugins:[// Compile javascript JSX syntax using inferno's own plugin['babel-plugin-inferno',{imports:true}]]}}]},{test:/\.ts+(|x)$/,// Compile ts and tsx extensionsexclude:/node_modules/,use:[{loader:'ts-loader',options:{getCustomTransformers:()=>({// inferno custom TSX pluginafter:[infernoTsx()]}),compilerOptions:{/* typescript compiler options */}}}]}]},resolve:{extensions:['.js','.ts','.tsx'],alias:{// This maps import "inferno" to es6 module entry based on workflowinferno:path.resolve(__dirname,'node_modules/inferno/dist',isProduction ?'index.dev.mjs' :'index.mjs')}},plugins:[newwebpack.DefinePlugin({'process.env':{'NODE_ENV':JSON.stringify(isProduction ?'production' :'development')}})]
Example ofRollup configuration:
constpath=require('path');constalias=require('@rollup/plugin-alias');const{babel}=require('@rollup/plugin-babel');constreplace=require('@rollup/plugin-replace');consttypescript=require('rollup-plugin-typescript2');consttransformInferno=require('ts-plugin-inferno').default;...Rollupconfig ...{ input:/* entry file */, plugins:[alias({resolve:['.js'],entries:[// This maps import "inferno" to es6 module entry based on workflow{find:'inferno',replacement:path.resolve(__dirname,'node_modules/inferno/dist',isProduction ?'index.dev.mjs' :'index.mjs')}]}),typescript({include:['*.ts+(|x)','**/*.ts+(|x)'],transformers:[()=>({after:[transformInferno()]})],tsconfig:'tsconfig.json',tsconfigOverride:{/* typescript compiler options */}}),babel({babelrc:false,sourceMaps:isDeploy,plugins:[// Compile javascript JSX syntax using inferno's own plugin['babel-plugin-inferno',{imports:true}]],babelHelpers:'bundled'})]}
Inferno always wants to deliver great performance. In order to do so, it has to make intelligent assumptions about the state of the DOM and the elements available to mutate. Custom namespaces conflict with this idea and change the schema of how different elements and attributes might work, so Inferno makes no attempt to support namespaces. Instead, SVG namespaces are automatically applied to elements and attributes based on theirtag name
.
If you want to contribute code, fork this project and submit a PR from your fork. To run browser tests you need to build the repos. A complete rebuild of the repos can take >5 mins.
$ git clone git@github.com:infernojs/inferno.git$cd inferno&& npm i$ npm run test:node$ npm run build$ npm run test:browser
If you only want to run the browser tests when coding, use the following to reduce turnaround by 50-80%:
$ npm run quick-test:browser# Compiles all packages and runs browser tests$ npm run quick-test:browser-inferno# Only compiles the inferno package and runs browser tests$ npm run quick-test:browser-debug# Compiles all packages and runs browser tests with "debug"
There is an InfernoJS Discord. You can join viahttps://discord.gg/SUKuhgaBpF.
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
About
🔥 An extremely fast, React-like JavaScript library for building modern user interfaces