source

'module-name' 모듈에 대한 선언 파일을 찾을 수 없습니다.'/path/to/module-name.module'에는 암묵적으로 '임의' 유형이 있습니다.

goodcode 2023. 3. 27. 23:09
반응형

'module-name' 모듈에 대한 선언 파일을 찾을 수 없습니다.'/path/to/module-name.module'에는 암묵적으로 '임의' 유형이 있습니다.

TypeScript 모듈 해결 방법을 확인했습니다.

저장소는 @ts-stack/di 입니다.디렉토리 구조를 컴파일하면 다음과 같습니다.

├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json

json이라고 썼어요."main": "dist/index.js".

Node.js에서는 모든 것이 정상적으로 동작하지만 TypeScript:

import {Injector} from '@ts-stack/di';

모듈 '@ts-stack/di'에 대한 선언 파일을 찾을 수 없습니다. '/path/to/node_modules/@ts-stack/di/index.js'에는 암시적으로 '임의' 유형이 있습니다.

그러나 다음과 같이 Import하면 모든 것이 작동합니다.

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

내가 뭘 잘못하고 있지?

여기 다른 두 가지 솔루션이 있습니다.

것이 - " - " 에서합니다.@types:

npm install -D @types/module-name

에러가 발생했을 는, 「변경」을 시험해 주세요.import에 대한 require:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

을 Import하는 Import.'foo', 도서관에도 없고,에도 없는 입니다.@types/foo패키지(확실히 에서 생성됨)Typeed Repository)를 사용하여 이 에러를 해소하려면 이 모듈을.d.ts가 TypeScript를 찾습니다..d.ts이 통상의 장소에 ..ts "files "", "files" "files" "files" "files" "files" "files" "files" "files" "files" "files" 에서 지정된 파일"tsconfig.json.

// foo.d.ts
declare module 'foo';

Import를 할foo it'll just be typed as 라고만 입력됩니다.any. . .


또는 사용자가 직접 입력한 내용을 롤링할 수도 있습니다.

// foo.d.ts
declare module 'foo' {
    export function getRandomNumber(): number
} 

그러면 올바르게 컴파일됩니다.

import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number

모듈에 완전한 타이핑을 제공할 필요는 없습니다.실제로 사용하고 있는 비트(및 적절한 타이핑이 필요한 경우)에 한정되어 있기 때문에 API의 양이 매우 적은 경우에는 특히 사용하기 쉽습니다.


반면에, and, libraries, 편, 니 다 import 핑 이 개 이 의 on the as타, hand핑이ings don youings other typ if libraries에 be없 imported라any, , you can add this to a file with a 를 사용하여 파일을 추가할 수 있습니다..d.ts확장:내선번호:

declare module '*';

이 방법의 장점(및 단점)은 무엇이든 Import할 수 있고 TS가 컴파일된다는 것입니다.

빠른 수정이 필요한 경우 Import 행 앞에 다음 내용을 추가합니다.

// @ts-ignore

자체 npm 패키지를 설치하는 경우

서드파티 패키지를 사용하고 있는 경우는, 아래의 답변을 참조해 주세요.

거 한 remove다제?.js부에서"main": "dist/index.js"package.json.

"main": "dist/index",

또한 TypeScript 문서에 따라 추가합니다.

"main": "dist/index",
"typings": "dist/index",

★★distTS 컴파일러가 모듈의 파일을 저장하는 곳입니다.

TypeScript는 기본적으로 Javascript의 제약이 없기 때문에 보다 명확하고 정확하게 하기 위해 규칙을 구현하고 코드에 유형을 추가하는 것입니다.TypeScript에서는 컴파일러가 코드를 체크하고 오류를 찾을 수 있도록 데이터를 기술해야 합니다.컴파일러는 일치하지 않는 타입을 사용하고 있는지, 범위를 벗어나 있는지, 또는 다른 타입을 반환하려고 하는지를 알려줍니다.따라서 TypeScript와 함께 외부 라이브러리 및 모듈을 사용할 경우 해당 코드의 유형을 설명하는 파일이 포함되어 있어야 합니다.이러한 파일을 확장자를 가진 형식 선언 파일이라고 합니다.d.ts npm을 사용하여 유형을 포함할 수 .npm install @types/module_namemodule_name을 클릭합니다.

에러를 하고 모듈을 는 Import하다를 사용합니다.import * as module_name from 'module-name'typings에 새 에 새 폴더를 .module_name.d.ts 쓰다declare module 'module_name'.tsconfig.json및 add " " " 。"typeRoots": [ "../../typings", "../../node_modules/@types"] compilerOptions하여) TypeScript에 및 수 있는 새 ( )을 합니다.스크립트 입력"exclude": ["../../node_modules", "../../typings"]파일로 이동합니다.tsconfig.json을 사용하다

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "sourceMap": true,
        "outDir": "../dst/",
        "target": "ESNEXT",
        "typeRoots": [
            "../../typings",
            "../../node_modules/@types"
        ]
    },
    "lib": [
            "es2016"
    ],
    "exclude": [
        "../../node_modules",
        "../../typings"
    ]
}

이렇게 하면 오류가 해소되고 최신 ES6 및 TypeScript 규칙을 준수할 수 있습니다.

다른 사용자가 이 글을 읽을 경우 .js 파일의 이름을 .ts로 변경해 보십시오.

편집: 추가할 수도 있습니다."allowJs": true filetsconfig로 합니다.

이 방법은 다음과 같습니다.

1. index.d.ts 등의 선언 파일에 자신의 선언을 추가합니다(프로젝트 루트 아래에 있을 수 있습니다).

declare module 'Injector';

2. tsconfig.json에 index.d.ts를 추가합니다.

  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }

불행하게도 소포 작성자가 신고서를 가지고 귀찮게 굴지는 우리 손을 떠났습니다. 하는 은 '파일을 '는 이다.index.d.ts여기에는 다양한 패키지의 누락된 모든 선언 파일이 포함됩니다.

Index.d.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

해 주세요.tsconfig.js:

"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "index.d.ts" // this
  ]

돼요.typings.d.ts프로젝트의 루트 디렉터리에 있습니다.에는 그냥 이파파 add add add add add add add add add add add add add add add add inside inside를 추가해 주세요.declare module <module_name> 여기.module_nameImport하다'열어서'를 .tsconfig.json 및 을 지정합니다.typings.d.ts「」라고 하는 .include array.

// typings.d.ts 
declare module 'abc-module';

// tsconfig.json 
{
  ...
"include": [
    "src", "typings.d.ts"
  ]
}

// BOOM, Problem solved!!!

이 기술은 모듈에 "any"라는 이름의 유형을 제공합니다.상세한 것에 대하여는, https://medium.com/@steveruiz/using-a-subscript-in-a-typescript-project-3643490015f3 를 참조해 주세요.

이게 내가 일을 시작한 방법이야.

에는 '아까부터'라는 않은 했습니다.react-mobile-datepicker

안에 ./src에는 이/src/typings/.

a.를 작성하다.d.ts '파일'입니다./src/typings/react-mobile-datepicker.d.ts

c. 다음 코드를 사용하여 속성을 확장하고 안전하게 입력했습니다.

declare module 'react-mobile-datepicker' {
  class DatePicker extends React.Component<DatePickerProps, any> {}

  interface DatePickerProps {
    isPopup?: boolean;
    theme?: string;
    dateConfig?: DatePickerConfig;
  }

  export interface DatePickerConfig {
    prop1: number;
    pro2: string;
  }
  export default DatePicker;
}

d. 서드파티 라이브러리를 사용하는 경우와 마찬가지로 유형을 Import합니다.

import DatePicker, { DatePickerConfig, DatePickerConfigDate } from 'react-mobile-datepicker';

e를 변경합니다. 변경tsconfig.json다음 코드를 추가합니다.

{
  "compilerOptions": {
    //...other properties
    "typeRoots": [
      "src/typings",
      "node_modules/@types"
    ]
  }}

원본으로 사용한 기사에 대한 링크:

https://templecoding.com/blog/2016/03/31/creating-typescript-typings-for-existing-react-components

https://www.credera.com/insights/typescript-adding-custom-type-definitions-for-existing-libraries

이건 나한테 효과가 있었어.

// modules.d.ts 
declare module 'my-module';
// tsconfig.json 
{
  ...
  "include": [
    ...
    "src", "modules.d.ts"
  ]
}

// Import
import * as MyModule from 'my-module'
...
const theModule = MyModule()
...

Config 파일 TypeScript Config 됩니다.tsconfig.json의 쌍을 합니다.

"compilerOptions": {
"noImplicitAny": false
}

간단한 수정:

// example.d.ts
declare module 'foo';

개체의 인터페이스를 선언하는 경우(대규모 프로젝트에 권장) 다음을 사용할 수 있습니다.

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

어떻게 사용하는지? 간단해..

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this

"tsconfig.json" 옵션 " " " ""include" ★★★★★★★★★★★★★★★★★」"exclude"존재하지 않는 경우 루트 디렉토리에 통지하여 추가합니다.

// tsconfig.json
{
  "compilerOptions": {
  ...
  "include": [
    "src", 
  ],
  "exclude": [
    "node_modules", 
  ]
}

같은 했다."*.spec.ts" "exclude"「」를 "import"이 파일들에는 항상 문제가 있었다.

모듈을 설치했는데도 오류가 발생할 경우 해당 행 위에 다음 행을 추가하여 오류 메시지를 무시합니다.

// @ts-ignore: Unreachable code error

저는 여기서 모든 것을 시도해 보았지만, 제게는 전혀 다른 문제였습니다. 내 을 떼야 했다.*.d.tsImport:

import { SomeModuleType } from '3rd-party-module';

오류를 제거한 후...

설명:에서 모듈을 선언하는 경우*.d.ts이 파일은 Typescript 컴파일러에 의해 앰비언트 모듈(명시적으로 Import할 필요가 없는 모듈)로 자동으로 선택됩니다.지정이 완료되면import ... from ...이제 파일은 일반(ES6) 모듈이 되므로 자동으로 선택되지 않습니다.따라서 주변 모듈로 동작하도록 하려면 다음과 같이 다른 Import 스타일을 사용합니다.

type MyType: import('3rd-party-module').SomeModuleType;

@ktretyak과 @Retsam의 답변은 맞지만 완전한 실시간 예시와 제가 해야 할 일을 추가하고 싶습니다.

오류:

오류 TS7016(TS) 'react-region-select' 모듈에 대한 선언 파일을 찾을 수 없습니다.

'C:/Repo/node_modules/react-region-select/lib/RegionSelect.js'에는 암묵적으로 '임의' 유형이 있습니다.

★★를 해 보세요.npm i --save-dev @types/react-region-select' module'을하는 새로운 선언 이 존재하는 경우 또는 ' module'은 'description module'을 포함합니다.

.npm i --save-dev @types/react-region-select에러가 표시됩니다.

npm ERR! 코드 E404

npm ERR! 404를 찾을 수 없음 - GET https://registry.npmjs.org/ @types%2freact-region-select - 찾을 수 없음

npm ERR! 404 '@types/react-region-select@latest'가 npm 레지스트리에 없습니다.

npm ERR! 404 작성자를 도청하여 게시해야 합니다(또는 직접 이름을 사용하세요).

npm ERR! 404 npm tarball, folder, http url 또는 git url에서도 설치할 수 있습니다.

create-react-app에서는, 을 「을 작성합니다」라고 합니다.react-app-env.d.ts는 는나나 i i i i i i i 했다.declare module 'react-region-select';에러를 수신했습니다.

새 .src라고 하는typings이라는 파일도 있어요.react-region-select.d.ts

declare module 'react-region-select';

이렇게 하면 에러가 없어지고, 다음과 같이 Import 할 수 있습니다.

import RegionSelect from "react-region-select"; 

https://github.com/casavi/react-region-select

저는 많은 프로젝트에서 많은 패키지로 같은 문제에 직면해 있었습니다.그래서 자동으로 유형 선언을 생성하는 npm 패키지인 선언자를 만들었습니다.

기본적으로는 실행함으로써 동작합니다.tsc --emitDeclarationOnly배경화면.

npm부터 설치할 수 있습니다.

npm install --save-dev declarator
yarn add -D declarator

하다를 보세요.declarator.json 삭제:

{
  "$schema": "https://raw.githubusercontent.com/ArthurFiorette/declarator/master/schema.json",
  "packages": ["package1","package2"]
}

실행할 스크립트를 만듭니다.

포스트 인스톨 스크립트를 사용하면, 모든 패키지 인스톨시에 실행되므로 편리할 수 있습니다.

{
  "scripts": {
    "postinstall": "declarator"
  }
}

않을 많은 될 것이다.any 편이

상세내용 : https://github.com/ArthurFiorette/declarator#readme

대부분의 경우 의존관계에 따라 타입 패키지를 설치합니다.어느 쪽이든 tsconfig.json 파일에 allowJs -> true를 추가할 수 있습니다.

모듈이나 타입이 이미 설치되어 있고 IDE를 여러 번 새로고침하고 있는데도 잠시 당황했습니다.

은 터미널 하고 삭제한 것입니다.node_modules " " " 를 install그런 다음 편집기를 다시 로드합니다.

리액트 어플리케이션이 타이프스크립트로 기재되어 있는 노드 모듈에서도 같은 문제가 있었습니다.되었습니다.npm i --save my-module되어 javascript를 Client를 누릅니다

포함:

import * as MyModule from 'my-module';
let client: MyModule.Client = new MyModule.Client();

컴파일이 실패하고 다음 오류가 발생합니다.

Could not find a declaration file for module 'my-module'. 
'[...]/node_modules/my-module/lib/index.js' implicitly has an 'any' type.
  Try `npm install @types/my-module` if it exists or add a new declaration (.d.ts) file containing `declare module 'my-module';`

@types/my-module하지 않기 에, 「」를 했습니다.my-module.d.ts에 줄을 대다my-module수입하다하다

Namespace '"my-module"' has no exported member 'Client'.

클라이언트는 실제로 내보내고 js 앱에서 사용하면 정상적으로 동작합니다.이전 파일 있음을 ./node_modules/my-module/lib/index.js되어 있습니다.my-module/package.json "main"□□□□□□□□★

에게 암묵적인 은 신경쓰지 했다.any 저는 ,, 음, 음, 음, 음으로 설정합니다.falsetsconfig.json 삭제:

    "noImplicitAny": false,

제 경우, 이 문제를 해결하기 위한 3가지 방법이 모두 작동하지 않습니다.패키지에서 "type"을 "module"로 설정하면그러면 공통 대신 ES 모듈에 준거합니다.JS 구문패키지에 따라 ES Module 구문을 사용하여 해결할 수 있었습니다.json 설정.

import ws from 'ws'

export const create = (/** @type {string} */ accessToken) => {
    const WebSocket = ws;
    return new WebSocket(endpoint, accessToken, sslOptions);
}

이렇게 하면 'ws' 모듈에서 WebSocket 클래스를 사용할 수 있습니다.이것은 노드 모듈의 예이지만 기본적으로 모든 유형의 노드 모듈과 기능을 여기에 넣을 수 있습니다.

아래에서는 동작하지 않습니다.

  1. npm install -D @types/module-name
  2. const foo = require('module-name');
// index.d.ts
declare module 'foo';
  1. tsconfig.json에서의 설정
"noImplicitAny": true,
"allowJs": true

Webstorm에서 이 에러가 발생하고 있는 경우, 패키지를 인스톨 했을 때에 typescript 서비스를 재기동할 필요가 있는 경우가 있습니다.

  • 도움말 메뉴를 엽니다.
  • 액션 찾기
  • (Search(검))Restart Typescript Service

여기에 이미지 설명 입력

여기에 이미지 설명 입력

Retsam의 답변을 바탕으로 와일드카드를 사용할 수도 있습니다.*의 in ) ) 。yourDeclarations.d.ts파일을 하면 Import, Import 의 파일을 수 ..css ★★★★★★★★★★★★★★★★★」.webp 파일, 파일 이름을 수 .*파일 형식 선언의 선두에 표시됩니다.⤵이렇게 생겼을 거예요"

declare module '*.webp';

Import하다를 수 되었습니다..webp을 사용법

Import가 기능하지 않는 경우

import * as html2pdf from 'html2pdf.js';

코드에 코멘트를 붙이고 다음 스크립트파일을 공식 문서에 기재된 대로 index.html에 저장합니다.

<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>

사용 중인 컴포넌트에 html2pdf 변수를 선언합니다.

declare var html2pdf: any;

바로 그겁니다.나는 이틀 동안 이 문제에 매달렸지만, 마침내 해결되었다.

내게는 종속성을 Dev 종속성으로 설치하는 것이 효과적입니다.암묵적인 타입 체크를 무효로 하는 위의 솔루션은 기능하지만, 엄밀한 타입의 코드를 이용할 수 없게 되었습니다.따라서 모든 @types 모듈에 --save-dev 플래그를 부가하기만 하면 됩니다.당신에게도 도움이 되길 바랍니다.

may with with with with with with with with with with with with with파일을생성해야합니다..d.ts내선 번호

을 「」아래로 누릅니다.include의 의 키tsconfig.json 삭제:

  "include": [
    "src",
    "index.d.ts"
  ]

일을 해야 한다

.또, 「 」는 「 」입니다..d.ts내선 번호

::index.d.ts

을 「」아래로 누릅니다.include의 의 키tsconfig.json 삭제:

  "include": [
    "src",
    "index.d.ts"
  ]

Typescript 문서에서 다음을 수행합니다.

"typings" 필드는 "type"과 동의어이며 사용할 수도 있습니다.

또한 메인 선언 파일의 이름이 index.d.ts이고 패키지의 루트(index.js 옆)에 있는 경우에는 types 속성을 마킹할 필요가 없습니다.단, 마킹하는 것이 좋습니다.

어떤 이유에서인지 내 "type" 속성이 main.d.ts를 가리키고 있었습니다.패키지에서 라인을 제거했다.제이슨과 작동하기 시작했어

React, tsconfig.json에서 이 오류가 발생한 사용자의 경우,

"compilerOptions" : {
  ...
  "strict": false,
  ...
}

React의 create-react-app에서 자동으로 생성된 구성에서는 이 플래그가 true로 설정됩니다.

언급URL : https://stackoverflow.com/questions/41292559/could-not-find-a-declaration-file-for-module-module-name-path-to-module-nam

반응형