跳至內容

URL 導入 (urlImports)

此 API 目前為實驗性質,日後可能會有變動。

URL 導入是一項實驗性功能,允許您直接從外部伺服器(而非本地磁碟)導入模組。

警告:僅使用您信任的網域來下載並在您的機器上執行。請謹慎操作,並在該功能標記為穩定之前保持警覺。

要啟用此功能,請在 next.config.js 中加入允許的 URL 前綴

next.config.js
module.exports = {
  experimental: {
    urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
  },
}

然後,您可以直接從 URL 導入模組

import { a, b, c } from 'https://example.com/assets/some/module.js'

URL 導入可以運用在任何一般套件導入可使用的地方。

安全性模型

此功能在設計時,將安全性列為首要考量。首先,我們新增了一個實驗性旗標,強制您明確允許您接受 URL 導入的網域。我們正致力於進一步利用Edge Runtime將 URL 導入限制在瀏覽器沙盒中執行。

鎖定檔案

使用 URL 導入時,Next.js 會建立一個 next.lock 目錄,其中包含鎖定檔案和提取的資源。此目錄必須提交到 Git,而不是被 .gitignore 忽略。

  • 執行 next dev 時,Next.js 會下載所有新發現的 URL 導入並將其新增到您的鎖定檔案中。
  • 執行 next build 時,Next.js 將僅使用鎖定檔案來建置生產環境應用程式。

通常不需要網路請求,任何過時的鎖定檔案都會導致建置失敗。唯一例外是回應 Cache-Control: no-cache 的資源。這些資源在鎖定檔案中將會有一個 no-cache 的項目,並且在每次建置時都會從網路擷取。

範例 Skypack

import confetti from 'https://cdn.skypack.dev/canvas-confetti'
import { useEffect } from 'react'
 
export default () => {
  useEffect(() => {
    confetti()
  })
  return <p>Hello</p>
}

靜態圖片導入

import Image from 'next/image'
import logo from 'https://example.com/assets/logo.png'
 
export default () => (
  <div>
    <Image src={logo} placeholder="blur" />
  </div>
)

CSS 中的網址

.className {
  background: url('https://example.com/assets/hero.jpg');
}

資源導入

const logo = new URL('https://example.com/assets/file.txt', import.meta.url)
 
console.log(logo.pathname)
 
// prints "/_next/static/media/file.a9727b5d.txt"