實作
建立專案。
| 12
 
 | npm create vitecd vite-library-example
 
 | 
修改 main.js 檔,建立主程式。
| 12
 3
 4
 5
 6
 7
 
 | const hello = () => {console.log('Hello');
 };
 
 export {
 hello,
 };
 
 | 
新增 vite.config.js 檔。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 
 | import { resolve } from 'path';import { defineConfig } from 'vite';
 
 export default defineConfig({
 build: {
 lib: {
 entry: resolve(__dirname, 'main.js'),
 name: 'MyLib',
 fileName: (format) => `my-lib.${format}.js`,
 },
 rollupOptions: {
 external: [
 
 ],
 output: {
 globals: {
 
 },
 },
 },
 },
 });
 
 | 
修改 package.json 檔。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | {"name": "@memochou1993/vite-library-example",
 "version": "0.0.0",
 "type": "module",
 "scripts": {
 "dev": "vite",
 "build": "vite build",
 "preview": "vite preview"
 },
 "devDependencies": {
 "vite": "^3.0.9"
 },
 "files": [
 "dist"
 ],
 "main": "./dist/my-lib.umd.js",
 "module": "./dist/my-lib.es.js",
 "exports": {
 ".": {
 "import": "./dist/my-lib.es.js",
 "require": "./dist/my-lib.umd.js"
 }
 }
 }
 
 | 
執行編譯,並監聽變化。
| 1
 | npm run build -- --watch
 | 
預覽
使用 UMD 標準引入
修改 index.html 檔,將編譯好的套件引入。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | <!DOCTYPE html><html lang="en">
 <head>
 <meta charset="UTF-8" />
 <link rel="icon" type="image/svg+xml" href="/vite.svg" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Vite App</title>
 </head>
 <body>
 <div id="app"></div>
 <script src="dist/my-lib.umd.js"></script>
 <script>
 MyLib.hello();
 </script>
 </body>
 </html>
 
 | 
啟動服務。
使用 ES 模組引入
修改 index.html 檔,將編譯好的套件引入。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | <!DOCTYPE html><html lang="en">
 <head>
 <meta charset="UTF-8" />
 <link rel="icon" type="image/svg+xml" href="/vite.svg" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Vite App</title>
 </head>
 <body>
 <div id="app"></div>
 <script type="module">
 import { hello } from '/dist/my-lib.es.js';
 hello();
 </script>
 </body>
 </html>
 
 | 
啟動服務。
發布
登入 npm 套件管理平台。
測試發布,查看即將發布的檔案列表。
發布套件。
| 1
 | npm publish --access=public
 | 
使用
下載套件。
| 1
 | npm i @memochou1993/vite-library-example
 | 
修改 index.html 檔,將編譯好的套件引入。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | <!DOCTYPE html><html lang="en">
 <head>
 <meta charset="UTF-8" />
 <link rel="icon" type="image/svg+xml" href="/vite.svg" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>Vite App</title>
 </head>
 <body>
 <div id="app"></div>
 <script type="module">
 import { hello } from '@memochou1993/vite-library-example';
 hello();
 </script>
 </body>
 </html>
 
 | 
程式碼
參考資料