mowtheone
mowtheone

Reputation: 511

Unable to import node modules in React components

I am fiddling around with the following local drf-react setup. 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. Is this related to the react-dev-utils..? I would like to use webpack, but I fail to set it up properly. My frontend docker container won't compose, telling me to install webpack-cli. Help is much appreciated.

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

Upvotes: 1

Views: 4372

Answers (1)

Italo Borges
Italo Borges

Reputation: 2554

You should run the command npm install inside your frontend folder:

  • Open the terminal
  • Find the frontend folder
  • Inside of it run the command npm install

This command will install the dependencies related to your package.json file, which is inside the frontend folder.

Inside your React files you will put the whole path to the node_modules folder.

The idea of using node_modules is to make it easier to control your dependencies in your project. You should consider again using webpack to handle these files from 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:

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

Also, I have an example using Webpack + Bootstrap 4. You can use to build your own Webpack config for React and Redux.

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

Upvotes: 1

Related Questions