Reputation: 1357
I'm trying to import a local png image into my ts webpack project, and I get the following error.
TS2307: Cannot find module './images/logo.png'.
All my other modules are importing just fine, ie; my css, svg and ts files. It only seems to happen with png.
My webpack.config.js modules section
module: {
rules: [{
test: /\.ts$/,
use:['ts-loader']
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},{
test: /\.(woff|woff2|eot|ttf|svg)$/,
use: ['url-loader?limit=100000']
},{
test: /\.png$/,
use: ['file-loader']
}]
}
My tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"module": "CommonJS",
"target": "ES5",
"lib": ["DOM", "ES2015.Promise", "ES5"],
"allowJs": true,
"alwaysStrict": true
}
}
My import statement
import Logo from './images/logo.png';
My file structure
root
-src
--css
--images
---logo.png
--index.ts
--templates.ts
-package.json
-tsconfig.json
-webpack.config.js
Upvotes: 52
Views: 68850
Reputation: 9
Create a new file in the images directory with the name images.d.ts
and paste the below code.
declare module "*.png" {
export default value : any;
}
Upvotes: 1
Reputation: 133
Just create a d.ts file in root folder and copy below line.
declare module '*'
Restart the VScode, Good to go
Upvotes: -6
Reputation: 191
My mistake was that I excluded the reference react-app-env.d.ts:
/* eslint-disable spaced-comment */
/// <reference types="react-scripts" />
Eslint has pushed me to do this because of the spaced-comment rule.
Hope this helps someone.
Upvotes: 18
Reputation: 1357
I found the answer here. Webpack & Typescript image import
Here's what I did.
Added a new directory and a import-png.d.ts file
root
-typings
--custom
---import-png.d.ts
import-png.d.ts
declare module "*.png" {
const value: any;
export default value;
}
changed my file-loader module to this:
{
test: /\.(png|jpe?g|gif|jp2|webp)$/,
loader: 'file-loader',
options: {
name: 'images/[name].[ext]'
}
and now I can import with a statement like this:
import Logo from './images/logo.png'
Upvotes: 72