Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import file from public folder in react application?

I have a javascript file in the public folder and I want to import that file to components in the folder src/components.

projectFolder
  publicFolder
    index.html
    recorder.js
  srcFolder
    componentsFolder
       Speech.js
       Speech.css

But I can't do something like this in my component:

import Recorder from '../../public/recorder'

Because I get the following error:

Module not found: You attempted to import ../../public/recorder which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

As I've understood it's not allowed to import outside of /src directory, so I was wondering how I could "add a symlink" or if you know other ways to fix it.

like image 867
Joe Avatar asked Sep 24 '18 19:09

Joe


2 Answers

I believe you are using create-react-app ... this is a feature included in the ModuleScopePlugin, and you can disable it by ejecting the app and editing your webpack configuration (as described in this answer).

But beware, the feature exists for a reason. The create-react-app build tool only processes the src/ directory, so for example your JavaScript outside of here will not be transpiled by Babel. Furthermore, you're typically trying to avoid polluting the global scope if you're using a bundler like Webpack. So unless you've got a really specific reason why you'd need to do this, I'd say try and move it.

like image 108
djfdev Avatar answered Oct 13 '22 04:10

djfdev


You can modify the react-scripts config with the rescripts library

Create a file called .rescriptsrc.js in your root folder:

module.exports = config => {
  const scopePluginIndex = config.resolve.plugins.findIndex(
    ({ constructor }) => constructor && constructor.name === "ModuleScopePlugin"
  );

  config.resolve.plugins.splice(scopePluginIndex, 1);

  return config;
};
like image 25
Lukas Avatar answered Oct 13 '22 03:10

Lukas