
如何在 vite 打包的 umd 文件中使用暴露的方法
对于打包后的 umd 文件,在 html 中直接调用暴露的方法,通常的做法是将方法挂载到 window 对象上。除了这种方法,还有一种替代方案:
随着 vite 的广泛使用,我们可以采取另一种方式:
首先,在你的打包脚本中导出暴露的方法:
const canvaseditorfun = {
initeditorbyfile,
gethtml,
savecedata,
initeditorbydata
};
export default canvaseditorfun;然后,在 vite 配置文件中指定 output.external 选项:
build: {
lib: {
name,
filename: name,
entry: path.resolve(__dirname, 'src/main.ts')
},
rollupoptions: {
output: {
sourcemap: true,
external: ['my-external-module'],
}
}
}这样,在打包过程中,vite 不会将 my-external-module 包裹在 umd 模块中,而是将其视为一个外部依赖项。
在 html 中,你可以直接引用 my-external-module 并调用暴露的方法:
<script src="./umd.js"></script> <script> // 此时 canvasEditorFun 已暴露在全局作用域中 canvasEditorFun.initEditorByFile(); </script>
这种方式的好处是,它允许你在 html 中直接引用暴露的方法,而不需要使用 window 对象。需要注意的是,仅当 vite 检测到目标平台为浏览器时,此方法才有效。
以上就是如何在 Vite 打包的 UMD 文件中使用暴露的方法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号