Hugo 中使用 NPM 和 JSX

本文尝试在 Hugo 中使用 NPM JSX 和 MDX

hugo v0.124.1 为止,只有一个 pack 命令。用于生成 package.json 和 package.hugo.json

https://gohugo.io/commands/hugo_mod_npm_pack/

1
2
3
4
5
6
7
8
Various npm (Node package manager) helpers.

Usage:
  hugo mod npm [command] [flags]
  hugo mod npm [command]

Available Commands:
  pack        Experimental: Prepares and writes a composite package.json file for your project.

博客目录运行 hugo mod npm pack , 会读取并修改 package.json ,并生成 package.hugo.json 。没有 package.json 则生成 package.json 和 package.hugo.json 空模板。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  "comments": {
    "dependencies": {},
    "devDependencies": {}
  },
  "dependencies": {},
  "devDependencies": {},
  "name": "www.ftls.xyz",
  "version": "0.1.0"
}

然后在 package.hugo.json 添加需要的依赖,并运行 hugo mod npm pack , hugo 会把依赖写入 package.json ,然后 install 一下就行了。如果先 pnpm add -D preact ,目前测试看起来需要手动把 devDependencies 复制到 package.hugo.json 中才行,hugo mod npm pack 以 package.hugo.json 为主。

1
2
3
4
5
6
7
{
  "devDependencies": {
    "preact": "^10.20.2"
  },
  "name": "www.ftls.xyz",
  "version": "0.1.0"
}

如果想使用 JSX 功能,需要使用 Hugo v0.124.0 js.Build 新增功能。根据官网示例,新建 assets/js/test.jsx

1
2
3
4
5
6
7
8
// https://gohugo.io/hugo-pipes/js/
// https://github.com/gohugoio/hugoTestProjectJSModImports
import { render } from 'preact';

const App = () => <>Hello world!</>;

const container = document.getElementById('app');
if (container) render(<App />, container);

在能使用 Hugo 模板的文件中,例如 layouts/shortcodes/jsx.html 中使用 js.Build 。JSX automatic 代表自动导入, JSXImportSource 决定使用哪个库自动从中导入其 JSX 辅助函数,示例中使用 preact 。然后使用生成的 JS 文件即可。

1
2
3
4
{{ $js := resources.Get "js/test.jsx" | js.Build (dict "JSX" "automatic" "JSXImportSource" "preact") }}

<div id="app"></div>
<script src="{{ $js.RelPermalink }}"></script>

然后在 markdown 中使用 shortcode 就可在 Hugo 中使用 JSX 。就会加载一个 16.7kb 的 js 文件,显示 Hello world! 。