urlImports
URL 導入是一項實驗性功能,允許您直接從外部伺服器(而非本地磁碟)導入模組。
警告:僅使用您信任的網域來下載並在您的機器上執行。在此功能標記為穩定之前,請謹慎行事並保持警覺。
若要啟用此功能,請在 next.config.js
中新增允許的 URL 前綴:
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 導入可以用於所有一般套件導入能使用的地方。
安全模型
此功能的設計以安全性為最高優先考量。首先,我們新增了一個實驗性標記,強制您明確指定允許導入的網域。我們正在進一步努力,透過使用 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 中的 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)
// 輸出 "/_next/static/media/file.a9727b5d.txt"