简体   繁体   English

无法在React组件中导入节点模块

[英]Unable to import node modules in React components

I am fiddling around with the following local drf-react setup. 我在摆弄下面的本地drf-react设置。 I'm really new to react and javascript overall and got absolutely no idea why I cannot import axios or any other node module for that matter in my react components, except for the modules that already shipped with the cookiecutter project itself. 我对React和javascript的使用真的很陌生,完全不知道为什么我不能在我的react组件中导入axios或任何其他节点模块,除了cookiecutter项目本身已经附带的模块。 Is this related to the react-dev-utils..? 这和react-dev-utils ..有关吗? I would like to use webpack, but I fail to set it up properly. 我想使用webpack,但无法正确设置。 My frontend docker container won't compose, telling me to install webpack-cli. 我的前端docker容器无法编写,告诉我安装webpack-cli。 Help is much appreciated. 非常感谢您的帮助。

https://github.com/moritz91/drf-react-app https://github.com/moritz91/drf-react-app

You should run the command npm install inside your frontend folder: 您应该在前端文件夹中运行命令npm install

  • Open the terminal 打开终端
  • Find the frontend folder 查找前端文件夹
  • Inside of it run the command npm install 在其中运行命令npm install

This command will install the dependencies related to your package.json file, which is inside the frontend folder. 此命令将安装与package.json文件相关的依赖关系,该文件位于frontend文件夹中。

Inside your React files you will put the whole path to the node_modules folder. 在您的React文件中,您会将整个路径放入node_modules文件夹。

The idea of using node_modules is to make it easier to control your dependencies in your project. 使用node_modules的想法是使控制项目中的依赖关系更加容易。 You should consider again using webpack to handle these files from node_modules. 您应该再次考虑使用webpack处理来自node_modules的这些文件。

Wepack has a module called resolve which you have to fill with a list of directories and inside React components you don't need to use the whole path anymore, because Webpack will understand where to look: Wepack有一个名为resolve的模块,您必须在其中填充目录列表,而在React组件内部,您不再需要使用整个路径,因为Webpack会理解在哪里查找:

// ALIAS
resolve: {
   extensions: ['.js', '.jsx', '.scss'],
   modules: [
     'YOUR SOURCE FOLDER',
     'YOUR NODE MODULES FOLDER',
     'ANY OTHER FOLDER'
   ]
}

From the docs: 从文档:

Tell webpack what directories should be searched when resolving modules.

The documentation: https://webpack.js.org/configuration/resolve/ 文档: https : //webpack.js.org/configuration/resolve/

Also, I have an example using Webpack + Bootstrap 4. You can use to build your own Webpack config for React and Redux. 另外,我有一个使用Webpack + Bootstrap 4的示例。您可以用来为React和Redux构建自己的Webpack配置。

https://github.com/italoborges/webpack-bootstrap4-es6 https://github.com/italoborges/webpack-bootstrap4-es6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM