Ошибка can t resolve

Почему происходит данная ошибка и как её исправить?

ERROR in ./src/index.ts
Module not found: Error: Can't resolve './test' in '/Users/maks/Documents/MyProgramms/TestProject/src'
 @ ./src/index.ts 3:13-30

Файловая структура проекта:

структура проекта

index.ts

import { User } from './test';
let user = new User('ivan');

test.ts

export class User {
    name: string;

    constructor(name:string) {
        this.name = name;
    }
}

package.json

{
  "name": "testproject",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "build": "webpack --mode development --open"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "@types/es6-shim": "^0.31.37",
    "@types/express": "^4.16.0",
    "ts-loader": "^4.4.2",
    "typescript": "^2.9.2",
    "webpack": "^4.12.0",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4"
  }
}

webpack.config.js

module.exports = {
    entry: {
        main: './src/index.ts'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                    use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                loader: 'ts-loader'
            },
        ]
    },
    node: {
        fs: 'empty',
        net: 'empty'
    },
    target: 'node'
};

Так же пробовал импортировать через require, использовать awesome-typescript-loader и обновить webpack до последней версии.

The «Module not found: Error: Can’t resolve» error is a common issue faced by web developers using Webpack for bundling their Javascript applications. This error occurs when Webpack is unable to resolve the relative path to a module that is imported in the code. The issue can arise due to various reasons such as incorrect file path, missing files, or configuration issues with Webpack. In this article, we will look at some of the methods to fix this error and resolve the issue.

Method 1: Verify the file path

To fix the «Module not found: Error: Can’t resolve» issue in Webpack, you can verify the file path. This involves checking that the path to the file you are trying to import is correct. Here’s how to do it:

  1. First, check the path to the file you are trying to import. Make sure that the path is relative to the current file and that it includes the correct file extension.
import { myFunction } from './path/to/myFile.js';
  1. If the path is correct, check that the file exists in the specified location. You can use the fs module to check this.
const fs = require('fs');
const path = './path/to/myFile.js';

if (fs.existsSync(path)) {
  // file exists
} else {
  // file does not exist
}
  1. If the file exists, make sure that it exports the function or variable that you are trying to import. You can use the export keyword to do this.
// myFile.js
export const myFunction = () => {
  // function code here
}
  1. Finally, make sure that you are importing the correct function or variable from the file. You can use the correct syntax to import a specific function or variable.
import { myFunction } from './path/to/myFile.js';

By following these steps, you should be able to verify the file path and fix the «Module not found» issue in Webpack.

Method 2: Check for missing files

One way to fix the «Module not found» error in Webpack is to check for missing files. Here are the steps to do it:

  1. Check the file path in your import statement. Make sure it is correct and matches the file name and location.
import myModule from './path/to/myModule.js';
  1. Check the file extension. Make sure it matches the actual file extension. For example, if the file is a JavaScript file, it should have a «.js» extension.
import myModule from './path/to/myModule.js';
  1. Check the file name. Make sure it matches the actual file name. For example, if the file name is «myModule.js», the import statement should have the same name.
import myModule from './path/to/myModule.js';
  1. Check the file location. Make sure the file is located in the correct directory. If it is not, move the file to the correct directory.
import myModule from './path/to/myModule.js';
  1. Check for typos in the file path. Make sure there are no typos in the file path. If there are, correct them.
import myModule from './path/to/myModule.js';
  1. Check for missing files. If none of the above steps work, check if the file actually exists in the specified location. If it does not, create the file or move it to the correct location.
import myModule from './path/to/myModule.js';

By following these steps, you should be able to fix the «Module not found» error in Webpack.

Method 3: Update Webpack configuration

To fix the «Module not found» error in Webpack, you can update the Webpack configuration file to include the missing module’s path. Here are the steps to do it:

  1. Open the Webpack configuration file, usually named webpack.config.js.

  2. Find the resolve property, which is an object that specifies how Webpack resolves modules.

  3. Add the missing module’s path to the modules array. For example, if the missing module is located in the src/components directory, add the following line:

    resolve: {
      modules: ['node_modules', 'src/components'],
    }

    This tells Webpack to look for modules in the src/components directory in addition to the default node_modules directory.

  4. If the missing module is a file instead of a directory, you can add the file extension to the extensions array. For example, if the missing module is a file named utils.js, add the following line:

    resolve: {
      extensions: ['.js', '.jsx', '.json', '.scss'], // add .js if it is not already there
    }

    This tells Webpack to resolve files with the .js extension in addition to the default extensions.

Here is the complete code example:

module.exports = {
  // ...
  resolve: {
    modules: ['node_modules', 'src/components'], // add missing module's path here
    extensions: ['.js', '.jsx', '.json', '.scss'], // add missing file extension here
  },
  // ...
};

By updating the Webpack configuration file, you should be able to resolve the «Module not found» error with relative paths.

Method 4: Use absolute path for imports

To fix the webpack error «Module not found: Error: Can’t resolve (with relative path)», you can use absolute path for imports. Here’s how to do it:

  1. Create a jsconfig.json file in the root directory of your project. This file will tell your editor to use absolute paths for imports.
{
  "compilerOptions": {
    "baseUrl": "./src"
  },
  "include": ["src"]
}
  1. In your webpack configuration file, add the resolve property with the modules array. This array will tell webpack where to look for modules.
const path = require('path');

module.exports = {
  // ...
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules']
  }
};
  1. In your JavaScript files, use absolute paths for imports. For example:
import { myFunction } from 'components/myComponent';

Note: The path components/myComponent is relative to the file that’s importing it. With absolute paths, you can import it from anywhere in your project.

That’s it! With these steps, you should be able to fix the webpack error «Module not found: Error: Can’t resolve (with relative path)» by using absolute path for imports.

React is one of the most popular web development frameworks around. React is so popular because of the thousands of extensions and packages developers can download and integrate into their projects for added functionality. 

However, adding external packages to a project also adds uncalled for errors and bugs, especially when React can’t detect a package you’re trying to load into the project.

In this article, we’re talking about the “module not found: Error: can’t resolve” problem, which happens when React can’t load a package you’re referring to in your code.

Also read: How to fix ‘React-scripts: Command not found’ error?


Install the package

The first thing you should do is check if the package you’re using has been installed and added as a dependency. Depending on whether you’re using NPM or Yarn, you can install the required package using the following command.

npm install [package name]

Also, make sure that you’re importing the package before referring to it in your code. The same goes for any components that you’re using as well. 


Delete the node_modules folder

If installing the package right away isn’t helping, you can delete the entire node_modules folder and the package-lock,json file to refresh all dependencies in your project. This is effectively equivalent to reinstalling the project. Open a terminal, navigate to the project root directory and enter the following commands.

rm -rf node_modules
npm install

Try restarting the project now, and your modules should load just fine. 


Check your files

If you’re facing this error when importing local files or components, check to see if everything is in order. Your files end with the .js extension, and you’re importing them properly, keeping in mind the folder structure and the case you used when naming files. Use periods and slashes according to your folder directory structure when importing a file. 

Alternatively, you can mention the entire path just to be sure.

import Component from /components/subfolder/anyotherfolder

Also, make sure that your folder names don’t contain spaces, colons, or special characters like hashes or asterisks. 

Also read: Error: Function rcpp_precious_remove not provided by package rcpp: 3 Fixes

Describe the bug
I have the following project folder structure:

my-app/
├─ .webpack/
│  ├─ index.js
│  ├─ development.js
│  ├─ production.js
├─ node_modules/
├─ src/
│  ├─ index.tsx
├─ package.json

When I use .webpack/index.js to import a specific environment configuration I get the following error:

ERROR in main
Module not found: Error: Can't resolve './src' in '/Users/<path-to-project>/my-app'

To Reproduce

package.json

"@webpack-cli/serve": "^1.0.1-rc.0",
"webpack": "^5.0.0-rc.0",
"webpack-cli": "^4.0.0-rc.0",
"webpack-dev-server": "^3.11.0"

.webpack/index.js

module.exports = (env, arg) => {
  const { mode } = arg;
  const config = require(`./${mode}`);

  return config;
};

.webpack/development.js

module.exports = {
  entry:  path.resolve(__dirname, '../src/index.tsx'),
  output: {
    path: path.resolve(__dirname, '../build/'),
    filename: 'index.js'
  },
  devtool: 'source-map',
  devServer: {
    inline: true,
    port: 8080,
    contentBase: path.resolve(__dirname, '../src')
  },
  module: {
      rules: [
          { test: /\.tsx?$/, loader: 'awesome-typescript-loader' }
      ]
  },
  resolve: {
    modules: [
      '/Users/<path-to-project>/my-app/src',
      'node_modules'
    ],
    extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
  }
};
> webpack serve --config .webpack/index.js --mode development

Expected behavior

Expected the src directory to be resolved. If instead .webpack/index.js has the configuration there is no error that shows up.

Please paste the results of webpack-cli info here, and mention other relevant information

System:
    OS: macOS 10.15.6
    CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
    Memory: 451.53 MB / 16.00 GB
  Binaries:
    Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.14.8 - ~/.nvm/versions/node/v14.5.0/bin/npm
  Browsers:
    Firefox: 81.0
    Safari: 14.0
  Packages:
    case-sensitive-paths-webpack-plugin: ^2.3.0 => 2.3.0
    clean-webpack-plugin: ^3.0.0 => 3.0.0
    extract-css-chunks-webpack-plugin: ^4.7.5 => 4.7.5
    html-webpack-plugin: ^4.5.0 => 4.5.0
    webpack: ^5.0.0-rc.0 => 5.0.0-rc.0
    webpack-cli: ^4.0.0-rc.0 => 4.0.0-rc.0
    webpack-dev-server: ^3.11.0 => 3.11.0
    webpack-merge: ^5.1.4 => 5.1.4

react

In this article, you will learn about how to fix module not found: can’t resolve in React.

In React, module not found: can’t resolve is a common problem and often occurred. The reason behind this problem is not so serious but still, we need to find out why this kind of problem occurred. Recently, while working with React, I have faced this kind of issue and got myself stuck. After researching with it, I am able to figure out the problem and in this article, I will show you why this kind of problem occurred and how to fix it so that there is no obstacle happen in the journey of your learning React. First, let’s see what the error looks like in the below section:

module not found: can't resolve in React

Here, you can see that I am getting this error and in my case, the main reason behind it is that I misspelled my component name. The name of my component should be header instead of heater. To fix this error all I need to do is to write the component name in the right form. Let’s see the solution below:

Here, you can see that I have written the name of my component correctly while importing it and the moment I have done it, the error was completely gone and I am able to see my header component in the output. Let me show you the output also.

You can see that the program is running perfectly. While solving this error, I have figured out another reason behind this problem and that is the mismatch of the path of the component. let me explain it to you. Suppose, you have a component that is located in the component folder but you have imported it with only the component name. See the below example to understand it clearly.

module not found: can't resolve in React

Here, you can see that our header component is located in the components folder but while importing it we have mentioned only the header as the path. Can you guess what happens next? Let’s run our program and see what happens below:

module not found: can't resolve in React

You can see that we are getting that same error but this time for a different reason and let me guess, you have already know the reason behind this error and may also solve it. The solution for this case is to set the correct path of the component and in our case, the path will be ./components/header.

These are the reasons of occurring [fix module not found: can’t resolve] the error and If you get yourself stuck with this you may fix it by following the approaches that have been discussed in this article.

This guide is part of the “Common React Errors” series. It’s focused entirely on providing quick and easy solutions for React-related problems.

Понравилась статья? Поделить с друзьями:
  • Ошибка can t find language dll msain dll
  • Ошибка cannot communicate with scanner
  • Ошибка c80003fa центра обновления windows 7
  • Ошибка cannot call member function without object
  • Ошибка can t find language data