Cannot find module or its corresponding type declarations in React Native project - react-native

I'm trying to include paths aliases to my project in React Native.
In fact when I start the app it's working so I think my babel.config.js is ok, but in VSCode stills appear an error telling Cannot find module or its corresponding type declarations so I think I'm having my tsconfig.json wrong
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['.'],
alias: {
'#ali/assets': './src/assets',
'#ali/components': './src/components',
'#ali/colors': './src/theme/colors.ts'
}
}
]
]
}
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"lib": ["es2017"],
"allowJs": true,
"jsx": "react-native",
"noEmit": true,
"isolatedModules": true,
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": false,
"rootDir": ".",
"paths": {
"#ali/assets": ["./src/assets/*"],
"#ali/components": ["./src/components/*"],
"#ali/colors": ["./src/theme/colors"]
}
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
"extends": "expo/tsconfig.base"
}
Here's my file
src/screens/Login/index.tsx
import Wellcome from '#ali/components/LogIn/Wellcome'
import React from 'react'
import LoginForm from '../../components/forms/LoginForm'
export const LogIn = () => {
return (
<>
<Wellcome />
<LoginForm />
</>
)
}
export default LogIn
I can see my component Wellcome in my app, but in VSCode stills appear the error.

This is due to a tsconfig.json bad configuration.
You should add baseUrl and remove the starting "." from paths routes.
Try this:
"baseUrl": ".",
"paths": {
"#ali/assets/*": ["src/assets/*"],
"#ali/components/*": ["src/components/*"],
"#ali/colors/*": ["src/theme/colors"]
}

Related

Issue when importing vue components with jest

I am using jest for the first time and I have an error while importing vue components:
FAIL src/components/VBtn/__test__/VBtn.spec.ts
● Test suite failed to run
ReferenceError: __importDefault is not defined
> 1 | import VBtn from '../VBtn.vue';
| ^
2 | console.log(VBtn);
3 |
4 | /*
at Object.<anonymous> (src/components/VBtn/__test__/VBtn.spec.ts:1:1)
I use typescript so I have installed ts-jest
Here is my jest.config.js file:
/** #type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
moduleFileExtensions: ['ts', 'js', 'vue'],
preset: 'ts-jest',
transform: {
'^.+\\.vue$': '#vue/vue3-jest',
},
};
Here is the test file
import VBtn from '../VBtn.vue';
console.log(VBtn);
And here is my vuejs component (VBtn.vue):
<template>
<p>
Test
</p>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'VBtn',
});
</script>
Finally my tsconfig.json:
{
// Mapped from https://www.typescriptlang.org/tsconfig
"compilerOptions": {
// Type Checking
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"exactOptionalPropertyTypes": false,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"useUnknownInCatchVariables": true,
"noUncheckedIndexedAccess": true,
// Modules
"module": "ES2022",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
// Emit
"importsNotUsedAsValues": "error",
"inlineSources": true,
"newLine": "lf",
"noEmitHelpers": true,
"preserveConstEnums": true,
"removeComments": false,
"sourceMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
// Language and Environment
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["ES2022", "DOM"],
"target": "ES2022",
"useDefineForClassFields": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "test", "typings", "vite.config.ts"],
"references": [{ "path": "./tsconfig.node.json" }]
}
I have try to use Babel instead of ts-jest but the error is the same.
Sorry for the English mistakes. French is my native language

Problem in Path #Alias ​with Create-React-App

It just isn't finding the *.svg image, if I add a .TSX file it finds it, however, I already configured the *.svg .d.ts module, what's wrong?
ERROR in ./src/App.tsx 4:0-64
Module not found: Error: Can't resolve '#assets/imgs/teste.svg' in 'APP_NAME\src'
REACT-APP-IMPORT.D.TS
declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
TSCONFIG.JSON
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"#/*": ["src/*"],
"#assets/*": ["assets/*"]
},
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src", "src/react-app-import.d.ts", ".eslintrc"],
"exclude": ["node_modules", "dist", "build", "coverage"]
}
APP.TSX
import { ReactComponent as Logo } from '#assets/imgs/teste.svg';
export default function App() {
return (
<h1>
Hello World <Logo />
</h1>
);
}

How to shim a dependency in babel.config.js in react-native?

I've got a dependency I'd like to shim on my react-native project. I currently have the following code on my babel.config.js file:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
],
};
};
I've found the extension babel-plugin-module-resolver which seems to be helpful (any other alternative would work too) and tried to follow their examples but they didn't work
I've tried the following:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
root: ["./src"],
alias: {
'#dependency/to-shim': 'path/to-shimmer',
},
},
],
],
};
};
but that doesn't work
I've got the same error.
The code when running works correctly.
The problem is with build. The path still absolute.
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['.'],
alias: {
'#services': './src/services',
},
},
],
'react-native-reanimated/plugin',
],
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#services*": ["./src/services"]
},
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"esModuleInterop": true,
"importsNotUsedAsValues": "error",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": ["esnext"],
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitUseStrict": false,
"noStrictGenericChecks": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": false,
"target": "esnext"
},
"include": ["src"],
"exclude": [
"node_modules",
"commitlint.config.js",
"metro.config.js",
"jest.config.js",
"babel.config.js"
]
}
screenshot - should be relative after build

TS2307: Cannot find module '#/components/helper/utils/SimpleUtil.vue' or its corresponding type declarations

I work on Nuxt.js (Vue.js) project that uses TypeScript in VSCode. When importing components I'd like to cut off long paths to them. For example:
Instead of:
<script lang="ts">
import SimpleUtil from '../../../components/helper/utils/SimpleUtil.vue'
I'd like to have:
<script lang="ts">
import SimpleUtil from '#/components/helper/utils/SimpleUtil.vue'
Or:
<script lang="ts">
import SimpleUtil from 'components/helper/utils/SimpleUtil.vue'
But, when I use:
<script lang="ts">
import SimpleUtil from '#/components/helper/utils/SimpleUtil.vue'
There's an error:
The tsconfig.json file looks as following:
{
"compilerOptions": {
"target": "ES2018",
"module": "ES6",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": "./src",
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"types": [
"#types/node",
"#nuxt/types"
],
"resolveJsonModule": true
},
"paths": {
"~/*": [
"src/*"
],
"#/*": [
"src/*"
]
},
"include": [
"src/**/*.ts",
"src/**/*.vue"
],
"exclude": [
"src/node_modules",
"./node_modules",
".nuxt",
"dist"
]
}
The nuxt.config.js file looks as following:
export default {
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
title: 'Licota',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: ['~/assets/css/main.sass'],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [],
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
// https://go.nuxtjs.dev/typescript
'#nuxt/typescript-build',
// https://go.nuxtjs.dev/stylelint
'#nuxtjs/stylelint-module',
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'bootstrap-vue/nuxt',
],
// Axios module configuration (https://go.nuxtjs.dev/config-axios)
axios: {},
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
extractCSS: true,
},
srcDir: 'src/',
vue: {
config: {
productionTip: false,
devtools: true
}
}
}
How can I fix this issue?
This is the way that I declare paths in my jsconfig.json and it works for me:
"compilerOptions": {
"paths": {
"~/*": ["./*"],
"#/*": ["./*"],
"~~/*": ["./*"],
"##/*": ["./*"]
}
},
For more information you can check Nuxt TypeScript

how to get intellisense for methods of modules which are imported from an alias in .vue

In .vue and .js, I can enjoy the intellisense of vscode when developing.
But I found it doesn't work any more when I use an alias.
So I have searched for a while on blogs, found a solution, which is to configure a 'jsconfig.json' as below.
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"paths": {
"#/*": [
"src/*"
]
}
}
}
it worked in the .js file but didn't work in .vue file.
Does anyone know how to resolve it ?
Does work in .js
Not work in .vue
With vue-cli the alias is defined in the webpack-config (since #vue/cli uses webpack under the hood). So instead of jsconfig.json (delete it! just do it!) , I would:
1: Install the webpack resolver for eslint:
npm i eslint-import-resolver-webpack
2: Reference the plugin from your .eslintrc.js
"settings": {
"import/resolver": "webpack"
},
Done!
This is my complete .eslintrc.js just to be thorough:
module.exports = {
"settings": {
"import/resolver": "webpack"
},
parserOptions: {
parser: "babel-eslint"
},
extends: [
"eslint:recommended",
"plugin:vue/recommended"
],
"env": {
"browser": true,
"node": true
},
rules: {}
}
If any issues remains I would check the eslint-settings in vscode settings.json:
"eslint.enable": true,
"eslint.provideLintTask": true,
"eslint.workingDirectories": ["src"],
"eslint.validate": ["javascript","javascriptreact","vue"],