In my webpack config. I defined aliases
alias: {
components: 'src/components/',
config: 'src/config/'
}
When I import a module from this path an eslint error occurred.
import ShadowWrapper from 'components/ShadowWrapper'
error 'components' should be listed in the project's dependencies. Run 'npm i -S components' to add it import/no-extraneous-dependencies
Thanks, Pranav for the solution to this issue!
I add some code to this post to make it more practical for others.
First of all, in webpack config file I had defined this alias:
alias:{
components: path.resolve(__dirname, "src", "components")
}
That allow me to import components in my app in that way:
import NewsFeed from 'components/NewsFeed'
I have installed eslint-import-resolver-webpack plugin and put below code into .eslintrc.js or .eslintrc file :
settings: {
'import/resolver': {
alias: {
map: [
['components', './src/components']
]
}
}
That's it after running linter I got rid of Unable to resolve path to module 'components/NewsFeed' error message
Hope it will be helpful for some of you!
Here is what worked for me:
I installed eslint-import-resolver-alias as dev dependency:
npm install eslint-plugin-import eslint-import-resolver-alias --save-dev
In the Webpack config (in my case, it was Vue config, which is merged with Webpack config by Vue-cli), I added a few aliases:
resolve: {
extensions: ['.js', '.vue', '.json', '.less'],
alias: {
Site: path.resolve(__dirname, 'src/site'),
Admin: path.resolve(__dirname, 'src/admin'),
Common: path.resolve(__dirname, 'src/common'),
Assets: path.resolve(__dirname, 'src/common/assets'),
Configs: path.resolve(__dirname, 'src/common/configs'),
Style: path.resolve(__dirname, 'src/common/style')
}
}
In the .eslintsrc (or .eslintsrc.js, if you use that), I added the plugin and maps for these aliases, as follows:
"extends": ["plugin:import/recommended"],
"settings": {
"import/resolver": {
"alias": {
"map": [
["Site", "./src/site"],
["Admin", "./src/admin"],
["Common", "./src/common"],
["Assets", "./src/common/assets"],
["Configs", "./src/common/configs"],
["Style", "./src/common/style"]
]
},
"extensions": [".js", ".less", ".json", ".vue"]
}
}
I have added extensions for clarity and some good measures, which you can choose to not use for yourself.
Optional:
If you use VS Code and want these aliases working with the path intellisense, add a file jsconfig.json at the root, and specify your alias paths:
{
"compilerOptions": {
"target": "esnext",
"allowSyntheticDefaultImports": false,
"baseUrl": "./",
"paths": {
"~/*": ["src/*"],
"Root/*": ["src/*"],
"Site/*": ["src/site/*"],
"Admin/*": ["src/admin/*"],
"Common/*": ["src/common/*"],
"Assets/*": ["src/common/assets/*"],
"Configs/*": ["src/common/configs/*"],
"Style/*": ["src/common/style/*"]
}
},
"exclude": ["node_modules", "dist"]
}
There are additional settings for React and Typescript. Check the documentation at official site.
This issue can be resolved by using the eslint-import-resolver-webpack
Another way, without mapping aliases between webpack.config.js and .eslintrc.
You can use eslint-import-resolver-webpack and setup you .eslintrc file like this:
{
"extends": [
"plugin:import/recommended"
],
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"moduleDirectory": [
"node_modules",
"src"
]
}
}
}
}
Related
In a Vite project my config file is as follow
import { defineConfig } from 'vite';
import vue from '#vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
plugins: [vue()],
build: {
outDir: 'public',
},
resolve: {
alias: {
'#': path.resolve(__dirname, './src/components'),
'~': path.resolve(__dirname, './src'),
},
},
envDir: './',
envPrefix: 'STO_',
});
VSCode doesn't parse paths starting with # or ~ so if a file doesn't exists I don't even see the error, and I have bad auto-completion experience.
In PhpStorm I think there is a file called phpstorm.config.js where we can tell the editor how to parse such characters.
System.config({
paths: {
'#/*': './src/components/*',
'~/*': './src/*',
},
});
How can I fix this in VSCode? Is there a similar approach?
same approach as with a webpack
i configured mytsconfig.json (or alternatively jsconfig.json) to re-map the import statements:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"],
"#/*": ["./src/components/*"]
}
}
}
same answer as https://stackoverflow.com/a/39414291/13278193
I have my express.js project in monorepo. I want to add custom path alias to it.
The directory structure is:
./
server/
----> jsconfig.json
----> .eslintrc.js
----> src/
--------> index.js
--------> modules/auth
-------------> auth.controller.js
jsconfig.json
{
"compilerOptions": {
"module": "ES6",
"baseUrl": "./",
"paths": {
"#modules/*": [
"src/modules/*"
]
}
},
"exclude": ["node_modules"]
}
.eslintrc.js
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {
'no-console': 'error',
'no-debugger': 'error',
},
settings: {
'import/resolver': {
alias: {
map: [
['#modules/*', 'src/modules/*'],
],
extensions: ['.js', '.json'],
},
},
},
};
Simply, I just tried to import auth controller in my index.js file.
import authRoutes from '#modules/auth/auth.routes';
but I get the following error: Unable to resolve path to module '#modules/auth/auth.controller' .eslint import/no-unresolved
please, don't suggest to turn off the rule.
I've alreadyy tried eslint-import-resolver-jsconfig, but I got Cannot resolve jsConfig, SyntaxError } on 150.
Because I used monorepo, there was a problem for ESLint or even lint-staged.
So now I have only one project per repository and:
Added custom paths in jsconfig.json:
"paths": {
"#modules/*": [
"./src/modules/*"
]
}
Installed eslint-import-resolver-jsconfig and added the following configuration to the eslint.json:
"extends": [
"airbnb-base",
"eslint:recommended"
],
"plugins": ["import"],
"settings": {
"import/resolver": {
"jsconfig": {
"config": "jsconfig.json"
}
}
}
Installed the Babel plugin babel-plugin-module-resolver and added the following settings to the .babelrc:
"plugins": [
[
"module-resolver",
{
"alias": {
"#modules": "./src/modules"
}
}
]
]
But, again: This only works if you have one project per repository and all your configuration files (.*rc, package.json, etc) are in the root level.
To achieve the above I use the module-alias package.
After installing it as a normal dependency, npm i --save module-alias, add the following to your package.json:
"_moduleAliases": {
"#modules": "./src/modules"
}
That will basically define the mappings for all the aliases you want to define.
To make it work, you will now need to import the following on top of your application under index.js:
require("module-alias/register"); // If using commonJS
// or
import "module-alias/register"; // If transpiling es6
You are now all set and should be able to import your files with absolute paths looking as:
const authRoutes = require("#modules/auth/auth.routes")
// or
import authRoutes from "#modules/auth/auth.routes";
In case eslint still flags the unresolved path, you may need to update your jsconfig.json or tsconfig.json to contain the below:
"paths": {
"#modules/*": ["src/modules/*"]
}
You can find the package documentation and read more about its usage here.
My babel module resolver is not working with React-Native (neither does intellij in VScode)
Here, Is my babel config
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
And jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#assets": ["./assets"],
"#modules": ["./modules"],
"#config": ["./config"],
"#utils": ["./utils"]
}
}
}
I changed import for one of my files and this is the error I get when I executed the build command from Xcode
Error: Error loading assets JSON from Metro. Ensure you've followed
all expo-updates installation steps correctly. Unable to resolve
module ../../modules/store/components/Filters from
src/utils/Router.js:
None of these files exist:
Where I imported the file like this
import Filters from '#modules/store/components/Filters';
I had the same problem, I just removed the '#' from my aliases and it seems working fine now.
Here is my babel.config.js
module.exports = function (api) { ■ File is a CommonJS module; it may be converted to an ES6 module.
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
require.resolve("babel-plugin-module-resolver"),
{
root: ["./src/"],
alias: {
// define aliases to shorten the import paths
components: "./src/components",
containers: "./src/containers",
contexts: "./src/contexts",
interfaces: "./src/interfaces",
organizer: "./src/screens/organizer",
screens: "./src/screens",
},
extensions: [".js", ".jsx", ".tsx", ".ios.js", ".android.js"],
},
],
],
};
};
Try resetting the cache, if above suggested answers don't work
react-native start --reset-cache
This worked for me. For more info see here
Change your module-resolver's root to ['./src/']:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src/'], // <-- here ✅
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
I build a relay small webpack and typescript demo to play with.
If i run webpack with the webpack.config.js i get this error:
ERROR in ./js/app.ts
Module not found: Error: Can't resolve './MyModule' in '/Users/timo/Documents/Dev/Web/02_Tests/webpack_test/js'
# ./js/app.ts 3:17-38
I have no clue what the problem could be. The module export should be correct.
Folder Structure
webpack.config.js
const path = require('path');
module.exports = {
entry: './js/app.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{test: /\.ts$/, use: 'ts-loader'}
]
}
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"suppressImplicitAnyIndexErrors": true,
"strictNullChecks": false,
"lib": [
"es5", "es2015.core", "dom"
],
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist"
},
"include": [
"js/**/*"
]
}
src/app.js
import { MyModule } from './MyModule';
let mym = new MyModule();
console.log('Demo');
mym.createTool();
console.log(mym.demoTool(3,4));
src/MyModule.ts
export class MyModule {
createTool() {
console.log("Test 123");
}
demoTool(x:number ,y:number) {
return x+y;
}
};
src/index.html
<html>
<head>
<title>Demo</title>
<base href="/">
</head>
<body>
<script src="dist/bundle.js"></script>
</body>
</html>
Webpack does not look for .ts files by default. You can configure resolve.extensions to look for .ts. Don't forget to add the default values as well, otherwise most modules will break because they rely on the fact that the .js extension is automatically used.
resolve: {
extensions: ['.ts', '.js', '.json']
}
Tried all the suggestions above and it still didn't work.
Ended up being the tiniest detail:
In webpack.js, instead of:
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
The ordering should be:
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
Don't know why this is necessary, and to be quite honest, I'm beyond caring at this point...
Leaving this here for posterity, but I had this exact same issue and my problem was that my entry path was not relative but absolute. I changed entry from:
entry: 'entry.ts'
to
entry: './entry.ts'
I'm a bit late to the party, but is better to use:
resolve: {
extensions: ['.jsx', '.ts', '.tsx', '...']
}
... means that we'll not overwrite the default, only add to it
I'm using tsconfig instead of webpack which also compiles the submodule to a bundle (index.js).
The issue for me was that I had forgotten to compile the submodule (ie run tsc to generate index.js) before referencing it from outside.
I am trying, in es6, to import jsx files without requiring the .jsx extension:
import LoginErrorDialog from './LoginErrorDialogView';
Not:
import LoginErrorDialog from './LoginErrorDialogView.jsx';
While I have got webpack to import in this fashion successfully:
export default {
entry: './src/ui/js/app.js',
output: {
publicPath: '/',
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx'],
Eslint (esw webpack.config.* ./ --color --ext .js --ext .jsx) is still errorring.
Unable to resolve path to module './LoginView' import/no-unresolved
Any ideas?
I had the same issue here, and I fixed adding extra configuration in my .eslintrc.
In the extends property add:
"plugin:import/react"
In the settings property add:
"import/resolver": {
"node": {
"extensions": [".js",".jsx"]
}
}
Your .eslintrc will look like:
{
"extends": [
...
"plugin:import/react",
...
],
...
"settings": {
"import/resolver": {
"node": {
"extensions": [".js",".jsx"]
}
}
},
...
}
Add to rule section, below rule
"import/extensions": [0, { "js": "always" }]