The create-react-app imports restriction outside of src directory

前端 未结 17 1583
时光说笑
时光说笑 2020-11-22 13:20

I am using create-react-app. I am trying to call an image from my public folder from a file inside my src/components. I am receiving this error message.

相关标签:
17条回答
  • 2020-11-22 13:50

    the best solution is to fork react-scripts, this is actually mentioned in the official documentation, see: Alternatives to Ejecting

    0 讨论(0)
  • 2020-11-22 13:54

    Remove it using Craco:

    module.exports = {
      webpack: {
        configure: webpackConfig => {
          const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
            ({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
          );
    
          webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
          return webpackConfig;
        }
      }
    };
    
    0 讨论(0)
  • 2020-11-22 13:54

    This restriction makes sure all files or modules (exports) are inside src/ directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js, in following lines of code.

    // Resolve the issuer from our appSrc and make sure it's one of our files
    // Maybe an indexOf === 0 would be better?
         const relative = path.relative(appSrc, request.context.issuer);
    // If it's not in src/ or a subdirectory, not our request!
         if (relative.startsWith('../') || relative.startsWith('..\\')) {
            return callback();
          }
    

    You can remove this restriction by

    1. either changing this piece of code (not recommended)
    2. or do eject then remove ModuleScopePlugin.js from the directory.
    3. or comment/remove const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); from ./node_modules/react-scripts/config/webpack.config.dev.js

    PS: beware of the consequences of eject.

    0 讨论(0)
  • 2020-11-22 13:57

    I think Lukas Bach solution to use react-app-rewired in order to modify webpack config is a good way to go, however, I wouldn't exclude the whole ModuleScopePlugin but instead whitelist the specific file that can be imported outside of src:

    config-overrides.js

    const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
    const path = require("path");
    
    module.exports = function override(config) {
      config.resolve.plugins.forEach(plugin => {
        if (plugin instanceof ModuleScopePlugin) {
          plugin.allowedFiles.add(path.resolve("./config.json"));
        }
      });
    
      return config;
    };
    
    0 讨论(0)
  • 2020-11-22 14:01

    You need to move WC-BlackonWhite.jpg into your src directory. The public directory is for static files that's going to be linked directly in the HTML (such as the favicon), not stuff that you're going to import directly into your bundle.

    0 讨论(0)
提交回复
热议问题