反应延迟加载外部AMD模块

时间:2019-03-13 17:23:07

标签: reactjs webpack requirejs create-react-app

我的React应用在src/之外有外部资源,因此我退出了react-scripts并禁用了ModuleScopePlugin。 在resolve.alias中引用了外部库,并在整个应用程序中使用。

resolve.alias: {
  'genlib': path.resolve(fs.realpathSync(process.cwd()), 'lib/genlib/js/src'),
  'config': path.resolve(fs.realpathSync(process.cwd()), 'config/dev'),
  'messages': path.resolve(fs.realpathSync(process.cwd()), 'config/messages')
}

genlib是我正在尝试引用的外部库。

外部库是使用requirejs的AMD。

延迟存储库中的文件之一使用require加载类。

define('class1', ['require', ...], function(require, ...) {
  //
  require([variable], function()...)
});

上述要求是在运行时从Cannot find module 'xxx'抛出webpackEmptyContext

如果控制台了上面代码中的require,那么将记录下面的代码,而不是require函数。 困惑为什么要使用webpackEmptyContext而不是webpackContext功能

ƒ webpackEmptyContext(req) {
    var e = new Error("Cannot find module '" + req + "'");
    e.code = 'MODULE_NOT_FOUND';
    throw e;
}

除了添加别名并禁用ModuleScopePlugin之外,我没有更改任何webpack.config.js

需要在配置中添加或更改其他内容以延迟加载amd模块。

webpack v4.19.1
react-dev-utils v7.0.1

2 个答案:

答案 0 :(得分:0)

您将在babel-loader文件的返回对象中看到webpack.config.jsmodule -> rules array第一个代码是运行linter

    {
      test: /\.(js|mjs|jsx)$/,
      enforce: 'pre',
      use: [
        {
          options: {
            formatter: require.resolve('react-dev-utils/eslintFormatter'),
            eslintPath: require.resolve('eslint'),

          },
          loader: require.resolve('eslint-loader'),
        },
      ],
      include: [
          paths.appSrc,
          'paht/to/external-library/using/requirejs' <---- Add your external file path for loader to parse the AMD files
      ],
    }

类似地包含文件路径以测试JS文件的进入  test: /\.(js|mjs|jsx|ts|tsx)$/,

您可以尝试一下并检查吗?

答案 1 :(得分:0)

我已经使用ContextReplacementPlugin解决了。

在Webpack配置插件中添加了以下代码。

new webpack.ContextReplacementPlugin(/genlib[\\/]services/, /.*$/),

现在将使用services目录中的所有文件创建一个映射,并在需要时webpackContext加载文件。

相关问题