记录做前端微服务项目遇到的一些问题

1,942 阅读1分钟
  1. 使用create-react-app+ant design of react自定义主题会用到官方推荐的craco,使用single-spa引用/src目录外的文件会有下图这样的错误:
Module not found: You attempted to import ... which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

百度会搜到相关的解决办法,如下:

Play by the existing rules (move to src). But now you can know how to remove restriction: do eject and remove ModuleScopePlugin from webpack configuration file.

但是将react-scripts替换为craco之后,再eject执行craco run start命令并不会执行eject之后的webpack.config.js,所以此时需要在craco.config.js文件里使用overrideWebpackConfig,配置文件如下:

// craco.config.js
const CracoLessPlugin = require('craco-less');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: {
              '@layout-header-background': '#483D8B',
            },
            javascriptEnabled: true,
          },
        },
      },
    },
    {
      plugin: {
        overrideCracoConfig: ({ cracoConfig, pluginOptions, context: { env, paths } }) => {
          return cracoConfig;
        },
        overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths } }) => {
          webpackConfig.resolve.plugins = webpackConfig.resolve.plugins.filter(p => p.constructor.name !== 'ModuleScopePlugin');

          // throw new Error('error');
          return webpackConfig;
        },
        overrideDevServerConfig: ({ devServerConfig, cracoConfig, pluginOptions, context: { env, paths, proxy, allowedHost } }) => {
          return devServerConfig;
        },
        overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context: { env, paths, resolve, rootDir } }) => {
          return jestConfig;
        },
      },
      options: {},
    },
  ],
};