背景

最近项目更新了tocbot,结果发现报错了··

import tocbot from "tocbot" 提示no export? - 图1

一脸懵逼,于是问了一下 AI,AI 给出了三种解释以及解决方法。

解决

你遇到的错误可能是因为 TypeScript 无法正确解析 tocbot 模块的导出方式。tocbot 模块使用了 CommonJS 的导出方式,而 TypeScript 默认使用 ES 模块的导入方式。

为了解决这个问题,你可以使用以下几种方法之一:

方法 1: 使用 require 导入

你可以使用 require 语法来导入 tocbot,这在 CommonJS 模块中是常见的做法。

  1. const tocbot = require('tocbot');

方法 2: 使用 esModuleInterop(测试无效!)

你可以在 tsconfig.json 中启用 esModuleInterop 选项,这样 TypeScript 会自动处理 CommonJS 模块的导入。

  1. {
  2. "compilerOptions": {
  3. "esModuleInterop": true
  4. }
  5. }

然后你可以像这样导入 tocbot

  1. import tocbot from 'tocbot';

方法 3: 使用 import * as(测试有效)

你也可以使用 import * as 语法来导入 tocbot,这在处理 CommonJS 模块时是常见的做法。

  1. import * as tocbot from 'tocbot';

示例代码

以下是一个完整的示例,展示了如何使用 tocbot 并配置其选项:

  1. // 方法 1: 使用 require 导入
  2. const tocbot = require('tocbot');
  3. // 方法 2: 使用 import 导入(需要启用 esModuleInterop)
  4. // import tocbot from 'tocbot';
  5. // 方法 3: 使用 import * as 导入
  6. // import * as tocbot from 'tocbot';
  7. // 初始化 tocbot
  8. tocbot.init({
  9. tocSelector: '.js-toc',
  10. contentSelector: '.js-toc-content',
  11. headingSelector: 'h1, h2, h3',
  12. ignoreSelector: '.toc-ignore',
  13. hasInnerContainers: true,
  14. linkClass: 'toc-link',
  15. extraLinkClasses: 'extra-link-class',
  16. activeLinkClass: 'is-active-link',
  17. listClass: 'toc-list',
  18. extraListClasses: 'extra-list-class',
  19. isCollapsedClass: 'is-collapsed',
  20. collapsibleClass: 'is-collapsible',
  21. listItemClass: 'toc-list-item',
  22. activeListItemClass: 'is-active-li',
  23. collapseDepth: 6,
  24. scrollSmooth: true,
  25. scrollSmoothDuration: 420,
  26. scrollSmoothOffset: -100,
  27. headingsOffset: 100,
  28. throttleTimeout: 50,
  29. positionFixedSelector: '.js-toc',
  30. positionFixedClass: 'is-position-fixed',
  31. fixedSidebarOffset: 'auto',
  32. includeHtml: true,
  33. includeTitleTags: true,
  34. onClick: (e: MouseEvent) => {
  35. e.preventDefault();
  36. console.log('Link clicked');
  37. },
  38. orderedList: false,
  39. scrollContainer: null,
  40. skipRendering: false,
  41. headingLabelCallback: (headingLabel: string) => {
  42. return headingLabel.length > 20 ? headingLabel.substring(0, 17) + '...' : headingLabel;
  43. },
  44. ignoreHiddenElements: true,
  45. headingObjectCallback: (obj: object, node: HTMLElement) => {
  46. if (node.classList.contains('exclude-from-toc')) {
  47. return;
  48. }
  49. return obj;
  50. },
  51. basePath: '',
  52. disableTocScrollSync: false,
  53. tocScrollOffset: 20
  54. });
  55. // 销毁 tocbot
  56. // tocbot.destroy();
  57. // 刷新 tocbot
  58. // tocbot.refresh();

通过这些方法,你应该能够成功导入并使用 tocbot 模块。