I have an HTML file and some scripts that load some modules directly from esm.sh
, e.g.
我有一个HTML文件和一些脚本,可以直接从esm.sh加载一些模块,例如
import { x } from 'https://esm.sh/y'
When building with Vite, these dependencies are not downloaded / bundled, so when the page loads and the scripts are executed, then there is at least one additional request per such dependency (typically more since they get bounced around in esm.sh
), reducing page load speed measurably.
当使用VTE构建时,这些依赖项不会下载/捆绑,因此当页面加载和脚本执行时,每个此类依赖项至少有一个额外的请求(通常更多,因为它们在esm.sh中反弹),从而显著降低了页面加载速度。
I know the "standard" way is to simply install the modules and have the bundler bundle them properly. But I was wondering, if there is a way (for example a Vite plugin or some configuration) that would pre-download and bundle all such dependencies.
我知道“标准”的方法是简单地安装模块,并让捆绑器正确地捆绑它们。但我想知道,是否有一种方法(例如,Vite插件或一些配置)可以预先下载并捆绑所有这些依赖项。
更多回答
优秀答案推荐
Yes, there is a way to bundle remote modules with Vite. You can use the vite-plugin-remote-assets plugin. This plugin will download and bundle all remote assets, including those from esm.sh.
是的,有一种方法可以将远程模块与VTE捆绑在一起。您可以使用VITE-Plugin-Remote-Assets插件。该插件将下载并捆绑所有远程资产,包括来自esm.sh的资产。
To use the plugin, install it with the following command:
要使用该插件,请使用以下命令安装它:
npm install -D vite-plugin-remote-assets
NPM安装-D vite-plugin-远程资产
Then, add the following line to your Vite configuration file:
然后,将以下行添加到Vite配置文件中:
plugins: ['vite-plugin-remote-assets']
插件:[‘vite-plugin-emote-sets’]
You can also configure the plugin to download and bundle specific assets, or to exclude certain assets. For more information, see the plugin documentation: https://github.com/antfu/vite-plugin-remote-assets
您还可以将插件配置为下载并捆绑特定的资产,或排除某些资产。有关更多信息,请参阅插件文档:https://github.com/antfu/vite-plugin-remote-assets
Here is an example of a Vite configuration file that uses the vite-plugin-remote-assets
plugin:
以下是使用Vite-plugin-Remote-Assets插件的Vite配置文件的示例:
//vite.config
import { defineConfig } from 'vite'
export default defineConfig({
plugins: ['vite-plugin-remote-assets'],
remoteAssets: {
assets: [
'https://esm.sh/y',
],
outputDir: 'assets',
},
})
Or as it appears in the official documentation:
或如官方文件中所示:
// vite.config.ts
import RemoteAssets from 'vite-plugin-remote-assets'
export default {
plugins: [
RemoteAssets()
]
}
I hope this helps!
我希望这能帮到你!
更多回答
thanks for the suggestion, does this plugin handle import graphs or would it just treat the modules as static assets? a typical export from esm.sh, even in bundled mode looks like export * from "/v132/y@version/es2021/y.bundle.mjs"
, meaning merely downloading as if it was another static asset wouldn't help, as you would need to follow links and download and bundle the whole dependency graph.
谢谢您的建议,这个插件是处理导入图形还是只将模块视为静态资产?典型的从esm.sh导出,即使是在捆绑模式下,也类似于从“/v132/y@Version/es2021/y.bundle.mjs”导出*,这意味着仅仅将其作为另一个静态资产进行下载是没有帮助的,因为您需要跟踪链接并下载并捆绑整个依赖关系图。
我是一名优秀的程序员,十分优秀!