1

我正在尝试在标记的编辑器中获取 Katex, https://github.com/markedjs/marked/issues/1538 从上面的链接中获取了代码,效果很好!

const marked = require('marked');
const katex = require('katex');  // external

const renderer = new marked.Renderer();

function mathsExpression(expr) {
  if (expr.match(/^\$\$[\s\S]*\$\$$/)) {
    expr = expr.substr(2, expr.length - 4);
    return katex.renderToString(expr, { displayMode: true });
  } else if (expr.match(/^\$[\s\S]*\$$/)) {
    expr = expr.substr(1, expr.length - 2);
    return katex.renderToString(expr, { isplayMode: false });
  }
}

但我想将 katex 作为单独的模块加载,所以我尝试使用 webpack 中的外部组件:https ://webpack.js.org/configuration/externals/

output: {
      path: PATH(isDev),
      filename: "bundle.js",
      library: "BUNDLE",
      libraryExport: "default",
      libraryTarget: "umd",
      globalObject: "this",
    },
externals: {
      katex: {
        root: "katex",
        commonjs2: "katex",
        commonjs: "katex",
        amd: "katex",
      },
    },

但是上面代码中的 katex 是未定义的,但它在 HTML 文件之外可用。因为我添加了 katex js 文件

<script
        src="../katex/katex.min.js"
        integrity="sha384-g7c+Jr9ZivxKLnZTDUhnkOnsh30B4H0rpLUpJ4jAIKs4fnJI+sEnkvrMWph2EDg4"
        crossorigin="anonymous"
    ></script>

我想我在这里遗漏了一些东西......你能帮我吗?谢谢

4

1 回答 1

0

你能试一下吗:

externals: {
   katex: "katex"
},

注意 katex

请?


我用文件创建了一个本地演示:

-webpack.config.js

-src

--index.js

-dist

--index.html

文件:

webpack.config.js:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  externals: {
      katex: "katex"
  }
};

src/index.js

var katex = require("katex");

export function foo() {
    console.log(katex);
}

foo();

索引.html:

<!doctype html>
<html>
  <head>
    <title>External Demo</title>
    <script
        src="../node_modules/katex/dist/katex.min.js"
    ></script>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

控制台中的结果: {version: "0.12.0", render: ƒ, renderToString: ƒ, ParseError: ƒ, __parse: ƒ, …} 然后我可以在函数内部使用 katex foo

于 2020-07-29T12:06:30.800 回答