2.0.8 • Published 2 years ago
react-webpack-lazyloader v2.0.8
react-webpack-lazyloader
The webpack loader for fetch react component async
用于异步按需加载 React Component, 支持 Dll 按需加载,推荐在 微前端项目 或 大组件加载 或 服务端支持 H2 的时候使用
Installation
npm install react-webpack-lazyloader @loadable/babel-plugin -D
# or use yarn
yarn add react-webpack-lazyloader @loadable/babel-plugin --dev
How it works?
Use webpack pitch loader and inspired by style-loader.
- Origin Button
export default () => <button></button>
- Transformed Button after
react-webpack-lazyloader
import loadable from '@loadable/babel-plugin'
const Component = loadable(() => import('!!BUTTON_REQUEST'))
const Button = React.forward(function Button(props, ref) {
return <Component ref={ref} {...props} />
})
export default Button
Usage
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: [/\.lazy\.(tsx|jsx?)$/, /\/pages\/[^\/]+?\/index\.tsx$/],
loader: 'react-webpack-lazyloader',
options: {
lazyType: 'React.lazy',
fallbackRequest: paths.resolveApp('src/page-loading.tsx'),
chunkName: 'react-lazy-[name]-[contenthash:8]'
}
}
]
}
}
正常使用
import Button from 'react-webpack-lazyloader!./button'
// 按照正常逻辑使用
;<Button>button</Button>
结合 DllPlugin
使用 DllPlugin,会预先把 chunk 一个个分离好,在 main.js 中则会按照 dll chunk 进行加载,比较适合母子前端工程使用
例子请看:examples
注意: Dll 模式下的组件更新,不会热替换,可能需要 IPC (Dll watch <-> Dev Server),后续进行完善,或者对于需要频繁改动的依赖,不建议 chunk 至 DLL 中
Options
lazyType
使用 @loadable/component
还是 React.lazy
方式实现异步加载,其中 @loadable/component
支持 SSR
- Type:
'loadable' | 'React.lazy'
- Default:
'loadable'
fallback
需要是可以正确注入的表达式字符串,如 '"加载中"'
而不能是 '加载中'
可以是 <Spin/>
- Type:
string
- Default:
'null'
fallbackRequest
Suspend 中 fallback 参数的引用 element,如 /path/to/loading.js
,可以保证 /path/to/loading.js
被正确 loader 转换
loading.js
import * as React from 'react'
export default <Spin />
- Type:
string
- Default:
'null'
jsx
是否用 JSX 语法,否则用 React.createElement
- Type:
boolean
- Default:
false
chunkName
chunk name
- Type:
string
- Default:
null
exposeNamedList
需要暴露的组件
- Type:
string[]
- Default:
['default']
wrapExposeComponentRequest
- Type:
string
- Default:
null
Contributing
- Fork it!
- Create your new branch:
git checkout -b feature-new
orgit checkout -b fix-which-bug
- Start your magic work now
- Make sure npm test passes
- Commit your changes:
git commit -am 'feat: some description (close #123)'
orgit commit -am 'fix: some description (fix #123)'
- Push to the branch:
git push
- Submit a pull request :)
Authors
This library is written and maintained by imcuttle, yucong06@meituan.com.
License
MIT - imcuttle 🐟