简体   繁体   中英

error TS2307: Cannot find module 'marked' or its corresponding type declarations

I was performing a headless test in Cypress and had to run

npm install --save-dev start-server-and-test so the server can start and wait for the url to respond before running the test. And ever since I ran that command, my code has been throwing the error below. And I don't know if that's a coincidence.

Error: src/app/article/markdown.pipe.ts:2:25 - error TS2307: Cannot find module 'marked' or its corresponding type declarations.

2 import * as marked from 'marked';

and this is my markdown.pipe.ts file:

import { Pipe, PipeTransform } from '@angular/core';
import * as marked from 'marked';

@Pipe({name: 'markdown'})
export class MarkdownPipe implements PipeTransform {
  transform(content: string): string {
    return marked(content, { sanitize: true });
  }
}

I tried to delete the node_modules and package-lock.json then run npm install but that didn't solve the issue. I searched similar posts here on stackoverflow and some suggestions were to run

npm install -g marked and npm install --save-dev @types/marked which had solve some similar problems, but it didn't seem to solve mine.

Here is the git repository of the folder. https://github.com/Leealp/BugsFixed

How can I fix the issue?

First, add types for for the marked package

npm install --save @types/marked

Inside the index.d.ts file you can see a couple of variations of

export function marked(...

Which is a "named" export, not the "default" export (there is no default export)

So in markdown.pipe.ts import it as

import {marked} from 'marked'

First, add types for for the marked package

npm install --save @types/marked

Next, run

npm install marked

This works for me in my project.

as @Fody said, the simplest way to fix is to add dependency @types/marked

but, it caused another problem, you need to change invoke way, otherwise IDE or webpack(while packing project) would throw error

i checked the source code of marked , the followging way might fix your issue

// change before
import marked from 'marked';

...
marked(mdStr);
...

// changed
import { parse as mdParse } from 'marked/lib/marked.esm.js;

...
mdParse(mdStr);
...

BTW, to avoid the issue about path changed, you might need to lock the version of marked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM