简体   繁体   中英

[ERR_MODULE_NOT_FOUND]: Cannot find package imported

I would like to change import from ../../../db/index.js to db/index.js

在此处输入图像描述

I have already added this setting in my jsconfig.json but I still got this error.

{
    "compilerOptions": {
        "module": "commonjs",
        "baseUrl": "src"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

Finally found the right answer after trying different kinds of approaches. Eslint import resolver and babel import resolver seem to be not working.

Add the ff:

package.json

"imports": {
    "#root/*": {
        "default": "./src/*"
    }
},

If you want to access that import directy via ctr+click/left click create jsconfig.json

{
    "compilerOptions": {
        "target": "esnext",
        "module": "commonjs",
        "baseUrl": "./src",
        "paths": {
            "#root/*": ["./*"]
        }
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

Usage in your index.js :

import level1 from '#root/level1/index.js';

instead of:

import level1 from './level1/index.js';

https://marian-caikovski.medium.com/4-ways-to-avoid-double-dots-in-module-specifiers-f5b6086cd9d1

These are two very different things:

import { something } from '../../something' - local import (file you've created)

import { something } from 'something' - import from a package (eg installed with yarn add something

If you'd like to clean up your imports and be able to do something like:

import { something } from '@components/something' then you need additional plugins/setup. It's worth looking into babel-plugin-root-import for example.

There might be other plugins/tools to do that but I've never had the need do do that so I don't know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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