6
votes

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.

3

3 Answers

1
votes

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.

1
votes

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;
};
-5
votes

As i can see you want to import parent component in child component.

While defining path './' represents the current directory in which you are working so you can go one level up by following '../' for one level up and the same goes for the upper level directory.

So if you want to import from public folder inside Speech.js component you could do something like this.

// In Speech.js

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

Hope this will be useful to you.