反应懒负载外部AMD模块



我的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()...)
});

上面的要求是在运行时从webpackEmptyContext投掷Cannot find module 'xxx'

require从上面的代码合并时,则记录下面而不是需要函数。感到困惑为什么webpackEmptyContext是合并的,而不是webpackContext功能

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

我没有更改任何webpack.config.js,除了添加别名和禁用模块copeplugin。

在配置中需要添加或更改的其他内容到懒负载AMD模块。

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

我已经使用ContextReplacementPlugin

在WebPack配置插件中添加了下面的代码。

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

现在,创建了一个映射,并在services目录中的所有文件中创建了一个地图,并且webpackContext在需要时加载文件。

您将在webpack.config.js文件的返回对象中看到babel-loadermodule -> 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)$/,

您可以尝试一下并检查?

最新更新