Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)

webpack: Module not found: Error: Can't resolve (with relative path)

Your file structure says that folder name is Container with a capital C. But you are trying to import it by container with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.

Webpack can't resolve relative path import express static

You're using an absolute path

import getGraphAccessToken from "/javascripts/ssoAuthES6.js";
// ^ this will look in your topmost directory on your OS

The relative path, from commands.js, would be:

import getGraphAccessToken from "../../javascripts/ssoAuthES6.js";

Alternatively, you can set Webpack to look for modules from your root directory by adding the following to your webpack configuration:

{
// ...
resolve: {
modules: [path.resolve(__dirname, "src"), "node_modules"],
},
// ...
}

Then you can import from your project's root directory from anywhere, like so:

import getGraphAccessToken from "javascripts/ssoAuthES6.js";

Some other points:

  • Since you're setting the extensions: [".ts", ".tsx", ".html", ".js"], you don't need to provide file extensions for those imports
  • You specify .ts and .tsx in your webpack config, but you are using .js files. Consider removing the Typescript extensions
  • If you are using Typescript, you will need to update import paths in your tsconfig.json
  • You can consider import path aliases in both Webpack and Typescript to be more explicit that your imports are coming from your project root. Instructions here

How to Use Absolute Path for npm run build

In the Webpack configuration file, add resolve.alias in order to create aliases and to import modules more easily.

module.exports = {
//...
resolve: {
alias: {
Components: path.resolve(__dirname, 'src/components/')
}
}
}

For instance, all modules that live inside src/components/ can now use absolute paths.

And for the VS code to recognize the path

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"components/*": ["src/components/*"]
}
},
"exclude": ["node_modules"]
}

Unable to import module when using alias in package json

That question applies to nodejs, not React. You can add configurations to your React app with craco.

  1. Install craco with yarn or npm
yarn add @craco/craco

  1. Create a craco.config.js file in your project's root and insert your aliases
const path = require(`path`);

module.exports = {
webpack: {
alias: {
'#components': path.resolve(__dirname, 'src/components'),
'#x': path.resolve(__dirname, 'src/x'),
}
},
};

  1. Replace react-scripts under the scripts section in package.json to craco like this
 "scripts": {
"start": "craco start",
"build": "craco build",
...
},

  1. Restart the dev server and you should be able to use your aliases.


Related Topics



Leave a reply



Submit