I created a Vite based Vue library. This library should distribute a single component inside a .mjs file.
Library setup
I basically created a new Vue app via npm create vue
, moved every dependency to dev dependencies and added this to the package.json
"files": [
"dist"
],
"exports": {
".": {
"import": "./dist/computedRenderer.mjs",
"require": "./dist/computedRenderer.umd.cjs"
}
},
After that I added the following to my vite.config.ts file
build: {
lib: {
name: "mylib",
fileName: "computedRenderer",
entry: resolve(__dirname, './src/myComp/index.ts'), // index file exporting my component
},
rollupOptions: {
external: ["vue"],
output: {
globals: {
vue: "Vue",
},
},
},
}
Building the project should generate you a computedRenderer.mjs in the dist directory ( as expected ).
File server for testing purposes
I created a small Node server serving the static .mjs file
import cors from "cors";
import express from "express";
const port = 3_000;
express()
.use(express.json())
.use(cors())
.use(express.static('./public')) // directory contains the generated .mjs file
.listen(port, () => {
console.log(`Listening on port ${port}`);
});
When running the server and calling
http://localhost:3000/computedRenderer.mjs
you should get the file content
How I consume the component
In my main project I try to import the component dynamically during runtime like so
<script setup lang="ts">
import { onMounted } from "vue";
onMounted(async () => {
const source = 'http://localhost:3000/computedRenderer.mjs'; // example url
const { ComputedRenderer } = await import(source);
// ...
});
</script>
Unfortunately I get the following warning
The above dynamic import cannot be analyzed by Vite. See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.
and error
Uncaught (in promise) TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
Is my library setup wrong? Or how can I consume the component via url?
Please let me know if you need more information
from How to create Vite based Vue component library consumable via .mjs files?
No comments:
Post a Comment