0
点赞
收藏
分享

微信扫一扫

巧用 import.meta 实现热更新


import.meta

​import.meta​​ 是一个给 JavaScript 模块暴露特定上下文的元数据属性的对象,它包含了这个模块的信息。

​import.meta​​​ 对象是由 ECMAScript 实现的,它带有一个 ​​null​​ 的原型对象。这个对象可以扩展,并且它的属性都是可写,可配置和可枚举的。

<script type="module">
console.log(import.meta) // {url: 'http://127.0.0.1:5500/dist/index.html?a=1'}
</script>

它返回一个带有 ​​url​​ 属性的对象,指明模块的基本 URL。也可以是外部脚本的 URL,还可以是内联脚本所属文档的 URL。注意,url 也可能包含参数或者哈希(比如后缀?​#​

巧用 import.meta 实现热更新_热更新实现

应用场景

​import.meta.hot​

Pinia 是 vuex 新替代方案。Pinia 中热更新实现,借助 import.meta

import { defineStore, acceptHMRUpdate } from 'pinia'

const useAuth = defineStore('auth', {
// options...
})

// make sure to pass the right store definition, `useAuth` in this case.
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useAuth, import.meta.hot))
}

Vite 通过特殊的 ​​import.meta.hot​​​ 对象暴露手动 HMR API。
​​​https://github.com/vitejs/vite/blob/main/packages/vite/src/client/client.ts#L412​​

interface ImportMeta {
readonly hot?: {
readonly data: any

accept(): void
accept(cb: (mod: any) => void): void
accept(dep: string, cb: (mod: any) => void): void
accept(deps: string[], cb: (mods: any[]) => void): void

prune(cb: () => void): void
dispose(cb: (data: any) => void): void
decline(): void
invalidate(): void

on(event: string, cb: (...args: any[]) => void): void
}
}

vite HMR API:​​https://cn.vitejs.dev/guide/api-hmr.html​​

​import.meta.webpackHot​

​​module.hot​​​ 的一个别名,​​strict ESM​​​ 中可以使用 ​​import.meta.webpackHot​​​ 但是不能使用 ​​module.hot​​。

在 package.json 中设置 ​​"type": "module"​​ 会强制 package.json 下的所有文件使用 ECMAScript 模块

vuex 借助 webpack 模块热替换:​​https://webpack.docschina.org/guides/hot-module-replacement/​​​ vuex 提供 ​​hotUpdate​​ 方法:​​https://github.com/vuejs/vuex/blob/HEAD/src/store.js#L242-L243​​

if (import.meta.webpackHot) {
// 使 action 和 mutation 成为可热重载模块
import.meta.webpackHot.accept(['./mutations', './modules'], () => {
// 获取更新后的模块
// 因为 babel 6 的模块编译格式问题,这里需要加上 `.default`
const newMutations = require('./mutations').default
const newModules = require('./modules').default
// 加载新模块
store.hotUpdate({
mutations: newMutations,
modules: {
...newModules
}
})
})
}

URL()

​URL()​​​ 构造函数返回一个新创建的 ​​URL​​ 对象,表示由一组参数定义的 URL。

const url = new URL(url [, base])

  • ​url​​​ 是一个表示绝对或相对 URL 的 ​​DOMString​​​。如果​​url​​​ 是相对 URL,则会将 ​​base​​​ 用作基准 URL。如果 ​​url​​​ 是绝对URL,则无论参数​​base​​是否存在,都将被忽略。
  • ​base​​​ 可选。是一个表示基准 URL 的 ​​DOMString​​,在 url 是相对 URL 时,它才会起效。如果未指定,则默认为 ​​''​​。

二者结合使用

new URL('./relative-path', import.meta.url)

示例:获取图片

function loadImg (relativePath) {
const url = new URL(relativePath, import.meta.url)
const image = new Image()
image.src = url
return image
}
loadImg('../../images/1.jpg')

无需关心路径问题,自动根据当前 URL 进行转换。


举报

相关推荐

0 条评论