vivipure / TIL

Today I learned
0 stars 0 forks source link

[Vue] Vite 打包Vue 3组件 #4

Open vivipure opened 2 years ago

vivipure commented 2 years ago
 build: {
    lib: {
      entry: "packages/components/index.ts",
      name: "funui",
      formats: ["umd", "iife"],
      fileName: "funui.js",
    },
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: {
          vue: 'Vue'
        }
      }
    }
  },

在vite.config.ts中配置build.lib属性, 其中format为打包的格式,提供给html直接使用可以选择iife

需要注意的的是,打包Vue组件时不应该把Vue的相关依赖打包进去,否则会运行失败,所以在rollup中声明vue为外置依赖

还有组件中的css,不能设置为scoped

vivipure commented 2 years ago

在HTML中通过cdn直接使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.2.33/dist/vue.global.prod.js"></script>
    <script src="../../dist/funui.js.iife.js"></script>
    <link rel="stylesheet" href="../../dist/style.css">
    <style>
        #app {
            width: 100vw;
            height: 100vh;

        }
    </style>

</head>

<body>
    <div id="app">
        <fun-video src="https://www.runoob.com/try/demo_source/movie.mp4"></fun-video>    
        <div>
            <fun-button>1111</fun-button>
        </div>
    </div>
    <script>
        const {FunVideo, FunButton} = window.funui
        const app = Vue.createApp({
            components: {
                FunVideo: FunVideo,
                FunButton: FunButton,
            },
        }).mount('#app');
    </script>
</body>
</html>