动态导入
Examples
ext.js 支持 JavaScript 的 TC39 提议dynamic import proposal。你可以动态导入 JavaScript 模块(如 React 组件)。
动态导入相当于把代码分成各个块管理。Next.js 服务端动态导入功能,你可以做很多炫酷事情。
下面介绍一些动态导入方式:
1. 基础支持 (同样支持 SSR)
- import dynamic from 'next/dynamic'
- const DynamicComponent = dynamic(import('../components/hello'))
- export default () =>
- <div>
- <Header />
- <DynamicComponent />
- <p>HOME PAGE is here!</p>
- </div>
2. 自定义加载组件
- import dynamic from 'next/dynamic'
- const DynamicComponentWithCustomLoading = dynamic(
- import('../components/hello2'),
- {
- loading: () => <p>...</p>
- }
- )
- export default () =>
- <div>
- <Header />
- <DynamicComponentWithCustomLoading />
- <p>HOME PAGE is here!</p>
- </div>
3. 禁止使用 SSR
- import dynamic from 'next/dynamic'
- const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), {
- ssr: false
- })
- export default () =>
- <div>
- <Header />
- <DynamicComponentWithNoSSR />
- <p>HOME PAGE is here!</p>
- </div>
4. 同时加载多个模块
- import dynamic from 'next/dynamic'
- const HelloBundle = dynamic({
- modules: () => {
- const components = {
- Hello1: import('../components/hello1'),
- Hello2: import('../components/hello2')
- }
- return components
- },
- render: (props, { Hello1, Hello2 }) =>
- <div>
- <h1>
- {props.title}
- </h1>
- <Hello1 />
- <Hello2 />
- </div>
- })
- export default () => <HelloBundle title="Dynamic Bundle" />