Dim*_*iwa 7 javascript reactjs webpack react-router react-loadable
我们使用反应和反应可加载.
在我们的应用程序初始化期间,我们将验证该component.preload方法是否存在于<Route />我们定义的每个方法.
如果缺少该方法,我们会显示一条警告,指出该组件应该是可加载的.
我们使用webpack 4,有没有办法自动包装组件,所以我们不必手动完成它?
这是组件的外观:
/** MyComponent.js: page component */
export default () => <div>Hello world</div>;
Run Code Online (Sandbox Code Playgroud)
这是包含在可反应加载组件中的相同组件:
/**
* preconfigured react-loadable
* See https://github.com/jamiebuilds/react-loadable#how-do-i-avoid-repetition)
*/
import MyLoadable from '@scopped/react-loadable';
/** loadable component */
export default MyLoadable({
loader: () => import('./MyComponent'), /** import page component */
});
Run Code Online (Sandbox Code Playgroud)
<Route />中声明node_modules.<Resource />(来自react-admin)而不是声明<Route />我不确定这是正确的方法,但也许您可以编写某种 webpack 加载器来预处理您的文件,<Route />在文件中查找模式,识别它们渲染的组件的路径并将它们转换为可加载组件该信息。
这有点 hacky,但它应该可以工作(仅适用于导入,但您可以根据需要进行调整):
网页包配置:
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: [
"babel-loader", // Rest of your loaders
path.resolve(__dirname, 'path/to/your/loader.js')
]
}
}
Run Code Online (Sandbox Code Playgroud)
加载器.js:
module.exports = function (source) {
const routeRegex = new RegExp(/<Route.*component={(.*)}.*\/>/g);
let matches;
let components = [];
while (matches = routeRegex.exec(source)) {
components.push(matches[1]); // Get all the component import names
}
// Replace all import lines by a MyLoadable lines
components.forEach((component) => {
const importRegex = new RegExp(`import ${component} from '(.*)'`);
const path = importRegex.exec(source)[1];
source = source.replace(importRegex, `
const ${component} = MyLoadable({
loader: () => import('${path}')
});
`);
});
source = `
import MyLoadable from './MyLoadable';
${source}
`;
return source;
};
Run Code Online (Sandbox Code Playgroud)
这绝对是很hacky,但如果你坚持惯例,这可能会起作用。它转换这种文件:
import Page1 from './Page1';
import Page2 from './Page2';
export default () => (
<Switch>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
</Switch>
);
Run Code Online (Sandbox Code Playgroud)
进入这个文件:
import MyLoadable from './MyLoadable;
const Page1 = MyLoadable({
loader: () => import('./Page1')
});
const Page2 = MyLoadable({
loader: () => import('./Page2')
});
export default () => (
<Switch>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
</Switch>
);
Run Code Online (Sandbox Code Playgroud)
这个示例有一些问题(路径MyLoadable应该是绝对的,它仅在导入页面组件时才有效,可加载组件不在单独的文件中,这可能会导致重复,...)但您明白了
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |