programing

형식 스크립트의 svg 파일을 가져올 수 없습니다.

fastcode 2023. 3. 16. 21:57
반응형

형식 스크립트의 svg 파일을 가져올 수 없습니다.

»typescript(*.tsx): files 음음g 수 .files 다g svg 일 Import。

import logo from './logo.svg';

★★★★★★★★★★★★★★★★★★:[ts] cannot find module './logo.svg'. svg 파일입니다.<svg>...</svg>.

하...에서는....js파일 똑같은 수입 명세서로 문제없이 수입할 수 있습니다.ts transpiler에 어떤 으로든 svg 합니다.

ts파일로 작업하는 방법을 알려주시겠습니까?

웹 팩을 사용하는 경우 사용자 정의 유형 파일을 생성하여 이 작업을 수행할 수 있습니다.

다음 내용으로 custom.d.ts 파일을 만듭니다.

declare module "*.svg" {
  const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
  export default content;
}

, 그럼 여기에다가 더해져요.custom.d.ts로로 합니다.tsconfig.json와 같이

"include": ["src/components", "src/custom.d.ts"]

출처 : https://webpack.js.org/guides/typescript/ #http://https://webpack.js.org/guides/typescript/ #http://filename

사용법을 지적해 주셔서 감사합니다.require() 저 에는 이렇게

const logo = require("./logo.svg") as string;

*.tsx 파일에서는 정상적으로 동작합니다.

  • ★★★★★★★★★를 사용하고 있는 경우는create-react-app 2+: 문서

custom.d.ts(RedMatt 덕분에) 올바른 타입으로 파일(src dir의 루트 경로에 파일을 작성했습니다.

declare module '*.svg' {
  const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
  export default content;
}

svg-react-loader 또는 다른 것을 인스톨 합니다.

  • 메인 svg 로더로 사용
  • 또는 코드베이스를 이행할 때 작업부품(JS)을 터치하지 않으려면 Import 시 로더를 지정합니다.
import MySVG from '-!svg-react-loader!src/assets/images/name.svg'

그런 다음 JSX 태그로 사용합니다.

function f() { 
  return (<MySVG />); 
}

내가 찾은 솔루션:리액트 중JS 프로젝트의 react-app-env.d.ts 파일에서 다음과 같은 주석의 공백을 제거할 수 있습니다.

전에

// / <reference types="react-scripts" />

끝나고

/// <reference types="react-scripts" />

도와드리고 싶습니다

나는 이 문제에 대한 해결책을 찾기 위해 인터넷을 샅샅이 뒤졌다.이 스택 오버플로우 질문이 선두로 떠올랐지만, 어느 대답도 통하지 않았습니다.

마침내, 나는 몇 가지 다른 기술들을 시도함으로써 해결책을 찾을 수 있었다.

  1. 작성하다./globals.d.ts 파일./tsconfig.json empty.month.mpti.

  2. 안에 ★★★★★./globals.d.ts 파일, 추가: 파일, 파일:

declare module '*.svg' {
  const content: string;
  export default content;
}

Import가 ..svg스트링으로 표현해서 1등급 답변에서 발견한 문제입니다.

  1. ★★★의 tsconfig.json다음을 포함합니다.
{
  "files": ["globals.d.ts"]
}

바로 그거야. 내 경우엔 그게 효과가 있었어.주의하겠습니다. 이것은 바닐라로 되어 있습니다.JS 앱

create-react-app과 같은 방법으로 svgs 모듈을 선언할 수 있습니다.

리액트 앱

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

출처를 참조하다

스타터를 사용하고 있는 경우는, 반드시, 다음의 순서에 따라 주세요.react-app-env.d.ts츠키다

/// <reference types="react-scripts" />

웹 팩 및 custom.d.ts를 사용하지 않는 솔루션

저는 위의 솔루션 중 어느 것도 단독으로 작동하지 않았습니다.왜냐하면 현재 프로젝트에서는 웹 팩을 사용하지 않기 때문입니다.

로그의 출력을 조사해, 파일 작성(custom.d.ts), 설정 변경, 새로운 의존관계 설치 없이, 다음의 방법으로 작업을 실시했습니다.

const logo: string = require("../assets/images/logo.svg").default;

<img src={logo} alt="logo" />

svg 형식의 경우 추가해야 합니다..default단, png 포맷은 아닙니다.

모듈 또는 대응하는 타입 선언을 찾을 수 없습니다.| 타입 스크립트의 svg 파일을 Import 할 수 없습니다.

  1. ./custom.d.ts 파일에 다음 내용을 추가합니다.
declare module '*.svg' {
  const content: string;
  export default content;
}

혼란스러우시면 이 비디오를 보세요.https://www.youtube.com/watch?v=Skhgdp7R9Tk

RECT + typscript tutorial을 시도했을 때도 같은 문제가 있었습니다.
저에게 효과가 있었던 것은 다음과 같은 수입 명세서였습니다.

import * as logo from 'logo.svg'

package.json에 대한 나의 의존관계는 다음과 같습니다.

  "dependencies": {
    "react": "^16.8.4",
    "react-dom": "^16.8.4",
    "react-scripts-ts": "3.1.0"
  },

도움이 됐으면 좋겠는데

이를 위한 다른 방법이 있습니다. SVG 컴포넌트를 만드는 것입니다.내가 이걸 한 이유는 내가 공통적으로 사용하는 것이 거슬렸기 때문이다.JSrequire내 진술과 함께imports.

호프! 이게 도움이 될 거야

실제로 모든 단계를 시도했지만, 우리가 이해해야 할 것은 custom.d.ts 파일을 대응하는 SVG Import 폴더에 작성해야 한다는 것입니다.

ts 설정 파일

{
  "compilerOptions": {
    "target": "ES6",
    "jsx": "react",
    "module": "ESNext",
    "moduleResolution": "Node",
    "baseUrl": "./",
    "paths": {
      "@components/*": ["src/components/*"],
      "@styles/*": ["src/styles/*"],
      "@static/*": ["src/static/*"]
    },
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": ["src/**/*", "src/static/optional.d.ts"],
  "exclude": ["node_modules", "build"]
}

옵션.d.ts

declare module '*.svg' {
    import * as React from 'react';

    export const ReactComponent: React.FunctionComponent<React.SVGProps<
        SVGSVGElement
    > & { title?: string }>;

    const src: string;
    export default src;
}

마지막으로 공통 내보내기 파일:

import Logo from './images/logo.svg';
import BellDot from './images/bell-dot.svg';
import Logout from './images/logout.svg';
import pageNotFound from './images/page-not-found.png';

export {
    Logo,
    BellDot,
    pageNotFound,
    Logout
}

더 나은 아이디어:

여기에 이미지 설명 입력

    // eslint-disable-next-line spaced-comment
/// <reference types="react-scripts" />

만약 당신이 puglin slint를 사용하고 있다면, 그는 그것이 코멘트라고 생각하여 비활성화시켰을 수도 있지만, 당신이 필요로 하는 svg를 읽지 않기 위해 이 타입의 스크립트모듈은 회선을 비활성화 시키고 행복하세요.

저는 다음 행을 src/types/images.d.ts에 넣었을 때 동작했습니다.

declare module '*.svg';

다음과 같은 방법으로 이미지를 Import합니다.

import { ReactComponent as WifiIcon } from '../../../assets/images/Wifi.svg';

tsconfig.json에서

다음과 같은 complierOptions 옵션이 있습니다.

"compilerOptions": {
    "typeRoots": ["node_modules/@types", "src/types"]
}

도움이 됐으면 좋겠어요저는 CRA를 최신 버전으로 사용하고 있습니다.

저 같은 경우에는 이 모든 것들을 포함시켜야 했어요.react-app-env.d.ts내 안에서tsconfig*.json:

  "include": [
    "src/Router.tsx",        // my main entry point
    "src/global.d.ts",       // global stuff
    "src/react-app-env.d.ts" // react global stuff
  ]

그 외의 회답이 모두 기능하지 않는 경우는, IDE 를 재기동해 보겠습니다(VS 코드).제 경우엔 그걸로 해결됐어요.

웹 팩을 사용하는 경우,svg-inline-loader, 모듈을 에 추가합니다.webpack.config.js:

{
    test: /\.svg$/,
    loader: 'svg-inline-loader',
}

지은 후에 잘 작동한다.

IDE가 인터랙티브 오류를 보고하는 경우 다음을 추가하여 해결할 수 있습니다.//@ts-ignore:

//@ts-ignore
import logo from './logo.svg';

svg-module-webpack 문서

CRA 앱에 SVG 파일 Import

설정을 실시하지 않고 CRA 앱(create-react-app)에 SVG 파일을 Import 하는 경우는, 다음의 몇개의 방법을 사용할 수 있습니다.

방법 1

import { ReactComponent as MyIcon } from "./assets/images/my-icon.svg";
...
<MyIcon />

방법 2

import myIconFileName from './assets/images/my-icon.svg';
...    
<img src={myIconFileName} />

언급URL : https://stackoverflow.com/questions/44717164/unable-to-import-svg-files-in-typescript

반응형