React - 在 node_modules 中导入一个module

IT技术 node.js reactjs
2021-05-01 07:46:59

将module从 node_modules 导入 React 应用程序的正确方法是什么?

当我做: import MyModule from '../node_modules/my_module'

我得到: Module not found: You attempted to import ../node_modules/my_module 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 复制到 src/ 中?

注意:我在没有符号链接的 Windows 上。

2个回答

如果你想从node_modules中导入一些module,你只需要说,例如导入整个导出的module:

import React from "react";

或导入导出module的一部分:

import { Router } from "react-router"

“react”和“react-router”是 node_modules 文件夹中的module。

导入语法应该使用 {export name} from './';

但是如果您使用导出默认值,则可以只使用导出名称。

而且,从 npm 安装的module不需要路径。只需使用module名称

例如) import {React, Component} from 'react';