我需要将我的gatsbyjs生成的html上传到json Post Body中使用源代码的API(https://developers.hubspot.com/docs/docs/methods/methods/methods/templates/post_templates),我想逃脱盖茨比(Gatsby-html-in-in-in-in-in-in-in-in)。我尝试扩展gatsby的webpack,其中包括gatsby-node.js
exports.onCreateWebpackConfig = ({
stage,
// rules,
// loaders,
plugins,
actions,
}) => {
actions.setWebpackConfig({
module: {
rules:
stage === 'build' || stage === 'build-html'
? [
{
test: /.html$/,
loader: 'string-replace-loader',
options: {
search: '"',
replace: '"',
flags: 'g',
},
},
]
: [],
},
});
};
使用此WebPack Loader https://www.npmjs.com/package/string-replace-loader。这根本不起作用。但是,如果将测试更改为/.js$/
,我可以将" string-replace-loader"替换为JS文件中的文本。我的test: /.html$/
可能在生成HTML文件?
看起来盖茨比(Gatsby)并未直接使用WebPack渲染HTML,因此您使用的WebPack加载程序将无法使用。
相反,您可以在gatsby-node.js
中的onPostBuild
挂钩中挂钩,当生成HTML时,这将运行。然后,您可以使用glob
(WebPack依赖关系)之类的东西来查找所有HTML并逃脱它们。
这是一个快速示例,借助fs-extra
(Gatsby依赖关系):
const fs = require('fs-extra')
const glob = require('glob')
exports.onPostBuild = async () => {
const htmls = glob.sync('./public/**/*.html') // array of paths to any htmls in public
const escapeHtmls = htmls.map(async htmlPath => {
const content = await fs.readFile(htmlPath, 'utf-8')
const escaped = JSON.stringify(content)
// upload the escaped strings to your api,
// or write it to a local file with write file i.e `fs.writeFile(htmlPath, escaped)`
console.log(`${htmlPath} has been escaped.`)
})
return Promise.all(escapeHtmls).catch(e => console.log(e))
}