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

前端 未结 17 1899
时光说笑
时光说笑 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:36

    If you only need to import a single file, such as README.md or package.json, then this can be explicitly added to ModuleScopePlugin()

    config/paths.js

    const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
    module.exports = {
      appPackageJson: resolveApp('package.json'),
      appReadmeMD:    resolveApp('README.md'),
    };
    

    config/webpack.config.dev.js + config/webpack.config.prod.js

    module.exports = {
      resolve: {
        plugins: [
          // Prevents users from importing files from outside of src/ (or node_modules/).
          // This often causes confusion because we only process files within src/ with babel.
          // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
          // please link the files into your node_modules/ and let module-resolution kick in.
          // Make sure your source files are compiled, as they will not be processed in any way.
          new ModuleScopePlugin(paths.appSrc, [
              paths.appPackageJson,
              paths.appReadmeMD         // README.md lives outside of ./src/ so needs to be explicitly included in ModuleScopePlugin()
          ]),
        ]
      }
    }
    

提交回复
热议问题