
在 html 中调用 vite 打包后的 umd 方法
在 Vite 中打包 UMD 文件后,要直接在 HTML 中调用其暴露的方法,通常需要将方法挂载到 window 对象上。但是,有另一种方法可以实现此目的:
打包时,您可以在 Vite 配置中设置 output.globals 选项,将暴露的方法映射到全局变量。例如:
build: {
lib: {
name,
fileName: name,
entry: path.resolve(__dirname, 'src/main.ts')
},
rollupOptions: {
output: {
sourcemap: true,
globals: {
'./src/main.ts': 'canvasEditorFun'
}
}
}
}通过这种方式,打包后的 UMD 文件将包含类似以下内容的代码:
var canvasEditorFun = {...};
window.canvasEditorFun = canvasEditorFun;现在,您可以在 HTML 中使用 canvasEditorFun 变量来调用暴露的方法。例如:
立即学习“前端免费学习笔记(深入)”;
<script> canvasEditorFun.initEditorByFile(...); </script>
采用这种方法,您不需要将方法显式挂载到 window 对象上,而是可以直接通过全局变量访问。
以上就是如何避免在 HTML 中显式挂载 UMD 方法到 window 对象?的详细内容,更多请关注php中文网其它相关文章!
Windows激活工具是正版认证的激活工具,永久激活,一键解决windows许可证即将过期。可激活win7系统、win8.1系统、win10系统、win11系统。下载后先看完视频激活教程,再进行操作,100%激活成功。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号