Here's my approach using Vue3 and Vite:
Check out the example demo here
1. Simplify the main.ts (main.js)
View commit
Avoid creating and mounting the App in main.ts. Simply import and export it.
// /src/main.ts
import './assets/main.css'
import App from './App.vue'
export { App }
2. Adjust your dev index.html
View commit
Since main.ts is now passive, manually trigger app creation and mount it in your dev index.html
. This step also applies when integrating the library into another app.
<!-- /index.html -->
<body>
<div id="app"></div>
<script type="module">
import { createApp } from 'vue';
import { App as VueLibExample } from '/src/main.ts';
createApp(VueLibExample).mount('#app');
</script>
</body>
Use an alias to prevent conflicts with other imported apps.
3. Building the library in mode
View commit
The key concept is to "build your app using library mode". Refer to Vite documentation for detailed steps on setting up vite.config.js
and package.json
.
Essentially, this is how my vite.config.js
looks:
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
// Other configuration details...
Make sure to include or exclude dependencies like 'vue' as needed but I recommend including to avoid version conflicts.
This is my package.json
:
{
// Package details...
}
To build the library:
> yarn build
yarn run v1.22.21
// Build output info...
4. Integrating the library in an HTML page
View commit
Once you have the exported files, integrate them in any HTML web page like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
// Other head elements...
</head>
<body>
<div id="the-div"></div>
// Script imports and app mounting...
</body>
</html>
Note the special handling of importing CSS styles and libraries, as expected in the library JS.