You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SharePoint WebPart中正确引入并使用myst-parser?

在SharePoint SPFx WebPart中正确引入myst-parser的解决方案

问题背景

按照微软官方文档配置外部JS库,将myst-parser通过CDN引入SPFx WebPart,配置及代码如下:

原externals配置

"externals": {
  "myst-parser": {
    "path": "https://cdn.jsdelivr.net/npm/myst-parser@1.0.21/dist/myst.min.js",
    "globalName": "myst-parser"
  }
},

原WebPart代码

import * as myst from 'myst-parser';
const html = myst.mystParse('# Hello to the world!')

部署后出现报错,提示myst.mystParse is not a function。

错误原因

  1. 全局变量名配置错误:CDN加载的myst-parser实际在浏览器全局对象中暴露的变量是myst,而非配置中写的myst-parser
  2. 方法名调用错误:myst-parser提供的Markdown解析方法是parse,而非代码中使用的mystParse

正确配置及代码

1. 修正externals配置

修改globalName为myst:

"externals": {
  "myst-parser": {
    "path": "https://cdn.jsdelivr.net/npm/myst-parser@1.0.21/dist/myst.min.js",
    "globalName": "myst"
  }
},

2. 调整WebPart调用代码

将mystParse替换为parse:

import * as myst from 'myst-parser';
const html = myst.parse('# Hello to the world!');

3. 可选:添加TypeScript类型声明(解决类型报错)

若项目使用TypeScript,因myst-parser未提供官方类型定义,可在项目根目录创建typings.d.ts文件,添加以下内容:

declare module 'myst-parser' {
  export function parse(markdownContent: string): string;
  // 如需使用其他方法,可补充对应类型定义
}

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:42:49