【发布时间】:2022-11-23 12:05:49
【问题描述】:
在 React 中使用图像时,打字稿有问题,或者图像在站点上损坏。
为了解决这个问题,我尝试了:
- 将 url-loader 和 file-loader 添加到 webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BUILD_PATH = path.resolve(__dirname, './build'); const SRC_PATH = path.resolve(__dirname, './src/'); const PUBLIC_PATH = path.resolve(__dirname, './public') module.exports = { entry: SRC_PATH + '/index.tsx', output: { path: BUILD_PATH, filename: 'bundle.js', }, mode: process.env.NODE_ENV || 'development', resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], extensions: [ '.tsx', '.ts', '.js' ], }, devServer: { static: PUBLIC_PATH, }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: /\.tsx?$/, exclude: /node_modules/, loader: 'ts-loader' }, { test: /\.(css|scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, { test: /\.module.css$/, use: [ { loader: "css-loader", options: { modules: true, }, }, ], }, { test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 8192, }, }, { test: /\.(jpg|jpeg|png|gif|mp3|svg)$/, use: ['file-loader'] }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, 'public', 'index.html'), }), ], };- 将图像作为组件导入
import React from 'react'; import logo from './header-logo.svg'; import styles from './Header.module.scss'; export const Header = () => { return <header className={styles.header}> <img src={logo} /> </header> };- 在 src/types 目录中创建 images.d.ts 文件
declare module "*.svg" { const content: any; export default content; }- 我什至尝试了 svgr..
但没有任何帮助。如果我删除 images.d.ts 文件,typescript 在导入时无法检测到该模块。 When using images.d.ts, vscode does not show errors, but the picture is not displayed in the browser, and instead of the normal path, something strange data:image/svg+xml;base64,ZXhwb3J0IGRlZmF1bHQgX193ZWJwYWNrX3B1YmxpY19wYXRoX18gKyAiZWMzYzM1Nzg3YTljZTMyMzE4M2NmMzM2Y2EzMDBkOTkuc3ZnIjs=
为了以防万一,我附加了 tsconfig.json
{ "compilerOptions": { "baseUrl": "./", "outDir": "./build/", "noImplicitAny": true, "module": "es6", "target": "es5", "jsx": "react", "allowJs": true, "allowSyntheticDefaultImports": true, "moduleResolution": "node", "plugins": [ { "name": "typescript-plugin-css-modules" }, ], }, }我是新手,所以请不要严格判断愚蠢的错误。我将不胜感激任何建议!
【问题讨论】:
-
你没有使用像
create-react-app这样的现成解决方案,这让事情变得更难了 -
我想尝试配置 webpack,因为我想这对其他东西来说是必要的 :)
标签: reactjs typescript webpack frontend