Symlink node_modules for files outside src
Asked Answered
C

1

2

In my project I use a JSON file as a database (which is currently stored in local on my computer). It is modified by Node.js and some pieces of information are rendered with React in an import : import Data from 'myPath/appData.json'; I cannot have my database in the src folder because the build is static, and my databse must be dynamic. I get this error :

Failed to compile.
./src/components/Ligne1.jsx
Module not found: You attempted to import myPath/appData.json 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/.

I am now asking your help on how to add the symlink. I created the folder "appData" in node_modules with :

const fs=require('fs');
fs.symlink('.src/','.node_modules/app/',e=>{});
import Data from 'myPath/appData.json';

And using it in my component like :

import Data from 'appData';

but I also get the error :

Failed to compile.
export 'default' (imported as 'Data') was not found in 'appData'

I'm looking for a solution to ignore the restriction of the import outside src folder (symlink or something else : I already tried to change the configs of webpack but it didn't change anything) or another solution to get the information from my JSON file (which is currently stored in local on my computer).

Thank you for your time.

Contiguity answered 16/7, 2018 at 8:33 Comment(1)
Possible duplicate of The create-react-app imports restriction outside of src directoryDarin
C
1

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.

Chloris answered 29/10, 2018 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.