Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jackyu/b13b758ace21458b43f928aea9f3b73a to your computer and use it in GitHub Desktop.
Save jackyu/b13b758ace21458b43f928aea9f3b73a to your computer and use it in GitHub Desktop.
[筆記][錯誤解決] 修正使用 DOMPurify 套件造成 Next.js 編譯錯誤問題

[速記] 如果在 Next.js 專案中有使用 DOMPurify 套件,在編譯時會發生以下錯誤

Can't resolve 'canvas'
Can't resolve 'bufferutil'
Can't resolve 'utf-8-validate'

這是因為 DOMPurify 套件在編譯時會使用到 canvas 和 bufferutil 套件,但是這兩個套件在 Next.js Server Component 上是不支援的,所以會發生錯誤。

next.config.js 中加入以下設定即可解決

/** @type {import("next").NextConfig} */
module.exports = {
  ...
  webpack: (config) => {
    config.externals = [...config.externals, "canvas", "jsdom"];
    return config;
  },
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment