在Webpack 4中,我们可以使用import()标记动态生成页面块,以便我们可以将react组件转换为可加载反应的组件吗?

问题描述 投票:7回答:1

我们使用react和react-loadable

在我们的应用程序初始化期间,我们正在验证我们定义的每个component.preload都存在<Route />方法。

如果缺少该方法,我们会显示一条警告,指出该组件应该是可加载的。

我们使用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 */
});
  1. 我们的<Route />node_modules和不同的包装内宣布。
  2. 可以使用<Resource />(来自react-admin)而不是<Route />声明它
  3. 它们不是以ESM格式分发,而是仅以CJS(CommonJS)分发。
javascript reactjs webpack react-router react-loadable
1个回答
3
投票

我不确定这是否是正确的方法,但也许您可以编写某种webpack加载器来预处理文件,在文件中找到<Route />模式,识别它们渲染的组件的路径并将它们转换为可加载的组件有了这些信息。

这有点hacky但它​​应该工作(只有导入,但你可以调整它,因为你想符合你的要求):

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;
};

这绝对是hacky,但如果你遵守惯例,这可能会奏效。它转换这种文件:

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的路径应该是绝对的,它只在导入页面组件时才有效,可加载的组件不在一个单独的文件中,这可能会导致重复,......)但是你得到了这个想法

© www.soinside.com 2019 - 2024. All rights reserved.