5

I would like to use absolute imports to import any file relative to the root src directory. This is my folder structure:

example/
┣ public/
┃ ┣ index.html
┣ src/
┃ ┣ components/
┃ ┣ ┣ App.css
┃ ┣ ┣ App.js
┃ ┣ ┗ Todo.js
┃ ┣ api.js
┃ ┣ history.js
┃ ┗ index.js
┣ craco.config.js
┣ jsconfig.json

And here is my config

var path = require("path");
module.exports = {
  resolve: {
    alias: {
      src: path.resolve(__dirname, "src"),
    },
  },
};

import Todo from "src/components/Todo"

But I get this error.

Module not found: Can't resolve 'src/components/Todo' in 'C:\_MyFiles\Programming\example\src\components'


However if I change the config and import to reference a subfolder under src like this it works...

var path = require("path");
module.exports = {
  resolve: {
    alias: {
      components: path.resolve(__dirname, "src/components"),
    },
  },
};

import Todo from "components/Todo"


How can I get the 1st variation working, so the imports reference the src folder instead of its subfolders?

1 Answer 1

4

You can use:

resolve: {
  modules: [path.resolve('./src'), path.resolve('./node_modules')],
  extensions: ['', '.js', '.jsx']
}

This will create an alias for all the subdirectories in your src and node_modules folders as well as your src folder itself. So you'll be able to use

Import App from 'components/App'

and

Import history from 'history'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.