Getting below error
cannot find module @assets/logo-filled.png from src/component/index.tsx
if I replace import logo from @assets/logo-filled.png
with import logo from ../../../assets/logo-filled.png
This line of import is working fine while running the application. But while running the test scripts npm test
-> react-scripts test
the above error is popping up
test.test.tsx
import React from "react";
import { render } from "@testing-library/react";
import {Logo} from "../components/logo";
describe('Describe...', () => {
test('test ...', () => {
console.log('the test');
render(<Logo withoutText={true}/>);
expect(1).toBe(1)
});
});
Logo.tsx
import React from 'react';
import { Stack, Image, Text } from '@fluentui/react';
import { logoContainerStyles, textStyles } from './styles';
// ERROR thrown by below line
import logo from '@assets/icon-16.png';
// Works fine with below commented line
/** import logo from '../../../assets/icon-16.png'; */
export interface LogoProps {
withoutText?: boolean;
}
export const Logo: React.FC<LogoProps> = props => {
const { withoutText } = props;
return (
<Stack styles={logoContainerStyles} horizontalAlign="center">
<Image src={logo} alt="logo" width={64} shouldFadeIn={false} />
<Text styles={textStyles} variant="xLarge">
Hello StackOverflow
</Text>
</Stack>
);
};
ts.config.json
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"moduleResolution": "node",
"allowJs": true,
"jsx": "react",
"lib": ["esnext", "dom", "dom.iterable"],
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"outDir": "dist",
"noImplicitReturns": true,
"pretty": true,
"typeRoots": ["node_modules/@types"],
"baseUrl": "src",
"paths": {
"@assets/*": ["../assets/*"]
}
},
"include": ["src"]
}
Any kind of help will much be appreciated.
2
Answers
We need a little bit more details on your setup. But it has to do with tsconfig.json and it’s paths property. Also take a closer look at jest property in package.json, it is used to define aliases for tests.
In the
jest.config.js
use ,If you want use module aliases with
TypeScript