Vue3 / Vite: How to package components for publishing on npm
Asked Answered
S

1

11

I'm trying to export two web components in a public package on npm, using Vite with TypeScript.

Vite has a Library Mode which works well. The ESM and UMD files are both being transpiled into my /dist directory. My question is how to export the web components in the entry point file.

I have an entry point file called export.js

import AwesomeHeader from './components/AwesomeHeader.vue'
import AwesomeFooter from './components/AwesomeFooter.vue'

export default { // I feel like the problem is here.
    components: {
        AwesomeHeader: AwesomeHeader,
        AwesomeFooter: AwesomeFooter,
    }
}

The idea is that I'll npm publish the project and use it like this.

npm i @sparkyspider/awesome-components #(ficticious example)
import {AwesomeHeader, AwesomeFooter} from '@sparkyspider/awesome-components' // does not find

(AwesomeHeader and AwesomeFooter are not found as exports in the node_module, even though the JavaScript files are referenced / found)

My package.json below:

{
    "name": "@sparkyspider/awesome-components",
    "version": "1.0.8",
    "files": [
        "dist"
    ],
    "main": "./dist/awesome-components.umd.js",
    "module": "./dist/awesome-components.es.js",
    "exports": {
        ".": {
            "import": "./dist/awesome-components.es.js",
            "require": "./dist/awesome-components.umd.js"
        }
    },
    "scripts": {
        "dev": "vite",
        "build": "vue-tsc --noEmit && vite build",
        "serve": "vite preview"
    },
    "dependencies": {
        "vue": "^3.0.5"
    },
    "devDependencies": {
        "@vitejs/plugin-vue": "^1.2.2",
        "@vue/compiler-sfc": "^3.0.5",
        "typescript": "^4.1.3",
        "vite": "^2.3.3",
        "vue-tsc": "^0.0.24"
    },
}
Stagemanage answered 20/5, 2021 at 8:37 Comment(0)
Y
3

You are having object { component: ... } as default export, instead of exporting AwesomeHeader and AwesomeFooter, which you try to import.

export { AwesomeHeader, AwesomeFooter } in export.js will work.

More on export: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

And you can't destructure the default export: https://mcmap.net/q/223697/-destructuring-a-default-export-object

Yocum answered 20/5, 2021 at 11:1 Comment(1)
Haha, such a simple answer - but it worked!Stagemanage

© 2022 - 2024 — McMap. All rights reserved.