为 Nuxt 应用程序创建自定义 Markdown-it 插件会导致在浏览器中呈现时出现 TypeError

Creating a custom Markdown-it plugin for Nuxt application results in TypeError when rendering in browser

我正在创建一个 Nuxt.js 应用程序(使用 npx 和 create-nuxt 创建)来呈现 markdown(使用 markdown-it)。我为 markdown-it 创建了一个插件。该插件位于 "helpers" 目录中。

nuxt.config.js

...
modules: [
...,
  '@nuxtjs/markdownit',
 ]
],
...
markdownit: {
  preset: 'commonmark',
  injected: true,
  use: [
    '../helpers/MarkdownNGH',
    'markdown-it-div'
  ]
},

我的插件是'../helpers/MarkdownNGH'。我还添加了另一个插件 markdown-it-div 用于测试。该插件随 npm 安装。

helpers/MarkdownNGH

module.exports = function plugin (md) {
 md.rendered.rules.link_open = (tokens, idx, options, env, self) => {
  // Logic for replacing the links is not important for this question
 }
}

现在,当我 运行 npm run dev 服务器端渲染正常工作并且我的插件编辑降价渲染时。

问题出在浏览器端。在浏览器中加载页面会导致控制台中出现以下错误消息:

client.js?06a0:77
TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
    at Module.eval (MarkdownNGH.js?7e65:3)
    at eval (MarkdownNGH.js:67)
    at Module../helpers/MarkdownNGH.js (app.js:322)
    at __webpack_require__ (runtime.js:791)
    at fn (runtime.js:151)
    at eval (markdown-it.js?e563:6)
    at _callee2$ (index.js?f26e:51)
    at tryCatch (runtime.js?96cf:45)
    at Generator.invoke [as _invoke] (runtime.js?96cf:271)
    at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)

在我生成的app.js中有以下代码,所以它在编译中。

/***/ "./helpers/MarkdownNGH.js":
/*!********************************!*\
  !*** ./helpers/MarkdownNGH.js ***!
  \********************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
eval(...) // The error points to this line

我复制了 markdown-it-div 的开发方式 (https://github.com/kickscondor/markdown-it-div/blob/master/index.js),它在服务器端渲染和浏览器中都运行良好。我对 webpack 和相关的东西非常陌生,所以这可能只是某种配置问题等。

编辑: 我试过这个: 所以将 .babelrc 更改为

{
  "env": {
    "test": {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "node": "current"
            }
          }
        ]
      ],
      "sourceType": "unambiguous"
    },
    "dev": {
      "sourceType": "unambiguous"
    }
  }
}

但这并没有帮助。不确定我这样做是否正确。

这是@nuxtjs/markdownit 中的错误(或缺失的功能)。 有一个 PR:https://github.com/nuxt-community/modules/pull/323

合并 PR(或者你用它构建 markdownit)时,将插件代码更改为

export default function plugin (md) {
 md.rendered.rules.link_open = (tokens, idx, options, env, self) => {
  // Logic for replacing the links is not important for this question
 }
}