[Vue3] Vite using CDN to load the required library file – front end/back end – The cloud about Vite information is also very little, stepped on some pit, finally finished. Share it.

Copy the CDN link from the Element-Plus website, along with the CDN link from the VUE.

//index.html

    <script src="https://unpkg.com/vue@next"></script> <! --import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/lib/theme-chalk/index.css">
    <! -- import JavaScript -->
    <script src="https://unpkg.com/element-plus/lib/index.full.js"></script>
Copy the code

Download the package NPM I rollup-plugin-external-globals -d and configure the viet.config.js file

//vite.config.js

import externalGlobals from 'rollup-plugin-external-globals'

export default defineConfig({
    build: {rollupOptions: {external: ['vue'.'element-plus'].plugins: [
                externalGlobals({
                    vue: 'Vue'.'element-plus': 'ElementPlus',}),],}}})Copy the code

Configure it in main.js

//main.js

import ElementPlus from 'element-plus'

createApp(App).use(router).use(ElementPlus).mount('#app')
Copy the code

NPM Run Build, NPM Run serve. Fine, notice that there is no element-Plus package downloaded at this point. NPM run dev.

To see what it looks like in your development environment, download elemental-Plus, NPM I Elemental-plus-s, and follow the normal steps. So what’s the point of introducing a CDN like this? The meaning is to follow the normal development steps in the development environment. But once packaged, it takes the form of a CDN and does not package Element’s NPM package.

When you don’t configure

When not configured, the size of the JS file is very large.

After the configuration

After configuration, 600K is directly lost.

conclusion

Development is done as normal, but with a packaged configuration added. This will be automatically recognized when packaging, and instead of packaging the NPM package, it will become a link referencing the CDN.