【问题标题】:Symlink node_modules for files outside srcsrc 外部文件的符号链接 node_modules
【发布时间】:2018-12-23 18:06:58
【问题描述】:

在我的项目中,我使用 JSON 文件作为数据库(当前存储在我的计算机本地)。它由 Node.js 修改,一些信息在导入中使用 React 呈现:import Data from 'myPath/appData.json'; 我的数据库不能放在 src 文件夹中,因为构建是静态的,而且我的数据库必须是动态的。 我收到此错误:

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/.

我现在就如何添加符号链接向您寻求帮助。我在 node_modules 中创建了文件夹“appData”:

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

并在我的组件中使用它,例如:

import Data from 'appData';

但我也收到错误:

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

我正在寻找一种解决方案来忽略 src 文件夹之外的导入限制(符号链接或其他东西:我已经尝试更改 webpack 的配置,但它没有改变任何东西)或其他解决方案来获取信息从我的 JSON 文件(当前存储在我的计算机本地)中。

感谢您的宝贵时间。

【问题讨论】:

标签: node.js reactjs import symlink src


【解决方案1】:

此限制确保所有文件或模块(导出)都在src/ 目录中,实现在./node_modules/react-dev-utils/ModuleScopePlugin.js 中,在以下代码行中。

// 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();
      }

您可以通过

删除此限制
  1. 要么更改这段代码(不推荐)
  2. 执行eject,然后从目录中删除ModuleScopePlugin.js
  3. 或从./node_modules/react-scripts/config/webpack.config.dev.js 中评论/删除const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

PS:小心eject的后果。

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2016-08-02
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2016-01-24
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多