跳到主要內容

urlImports

此功能目前為實驗性質,可能會有所變動,不建議用於生產環境。請試用並在 GitHub 上分享您的意見回饋。

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 匯入的網域。我們正努力進一步發展,將 URL 匯入限制為使用 Edge Runtime 在瀏覽器沙箱中執行。

鎖定檔

使用 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 中的 URL

.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"