我们使用react和反应可加载。
在应用程序初始化期间,我们要验证我们定义的每个<Route />是否存在component.preload方法。
如果缺少该方法,我们将显示一个警告,显示组件应该是可加载的。
我们使用webpack 4,是否有一种自动包装组件的方法,所以我们不需要手动完成它?
以下是组件的样子:
/** MyComponent.js: page component */
export default () => <div>Hello world</div>;这是包装在一个反应可加载组件中的同一个组件:
/**
* 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 */
});<Route />是用node_modules声明的,并且是在不同的包中声明的。<Route />声明。发布于 2019-02-25 13:18:33
我不确定这是不是正确的方法,但也许您可以编写某种webpack加载程序,对文件进行预处理,在文件中找到<Route />模式,确定它们呈现的组件的路径,并使用这些信息将它们转换为可加载的组件。
这有点麻烦,但它应该可以工作(只适用于导入,但您可以根据需要对其进行调整):
Webpack配置:
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: [
"babel-loader", // Rest of your loaders
path.resolve(__dirname, 'path/to/your/loader.js')
]
}
}loader.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;
};这绝对是无趣的,但如果你坚持惯例,这是可行的。它转换这种文件:
import Page1 from './Page1';
import Page2 from './Page2';
export default () => (
<Switch>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
</Switch>
);进入这个档案:
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>
);这个例子有一些问题( MyLoadable的路径应该是绝对的,只有当页面组件被导入,可加载的组件不在单独的文件中,这可能导致重复,.)但你知道
https://stackoverflow.com/questions/54864023
复制相似问题