
如何在 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 并调用暴露的方法:
这种方式的好处是,它允许你在 html 中直接引用暴露的方法,而不需要使用 window 对象。需要注意的是,仅当 vite 检测到目标平台为浏览器时,此方法才有效。










