在同一个GitHub 讨论中有一个更简单更优雅的解决方案
require-esm.js
在根文件夹(与 package.json 相同的位置)中创建:
// Source: https://stackoverflow.com/a/71344589/2078908
const esm = require('esm')
const fs = require('fs')
const Module = require('module')
// Node: bypass [ERR_REQUIRE_ESM]
const orig = Module._extensions['.js']
Module._extensions['.js'] = function (module, filename) {
try {
return orig(module, filename)
} catch (e) {
const content = fs.readFileSync(filename, 'utf8')
module._compile(content, filename)
}
}
const _esmRequire = esm(module, {
cjs: true,
mode: 'all',
})
// don't pollute Module
Module._extensions['.js'] = orig
module.exports = function esmRequire(id) {
return _esmRequire(id).default
}
然后gatsby-config.js
像这样使用它:
require.esm = require('./require-esm')
module.exports = {
.......
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: ['.mdx', '.md'],
rehypePlugins: [
// Generate heading ids for rehype-autolink-headings
[require.esm('rehype-slug')],
// To pass options, use a 2-element array with the
// configuration in an object in the second element
[require.esm('rehype-autolink-headings'), { behavior: "wrap" }],
],
}
},
.......
}
更新
经过一些测试后,我将上面的代码简化为几行。它仍然适用于我的设置。
require.esm(...)
像这样使用gatsby-config.js
:
const requireEsm = require('esm')(module)
require.esm = id => requireEsm(id).default
module.exports = {
.......
rehypePlugins: [
// Generate heading ids for rehype-autolink-headings
[require.esm('rehype-slug')],
.......
}