How to use Vue web components (generated by Vue-CLI 3) inside another Vue project?

Viewed 848

I Can Use web-components that generated by Vue-CLI 3 build command (vue-cli-service build --target wc --name foo ./src/App.vue) as a stand-alone component in a webpage like this:

<script src="https://unpkg.com/vue"></script>
<script src="./foo.js"></script>

<foo></foo>

BUT When I import this component inside another Vue project:

import Vue from 'vue'
import foo from 'foo'

I get this Error:

Uncaught ReferenceError: Vue is not defined

The Vue CLI 3 documentation says that:

In web component mode, Vue is externalized. This means the bundle will not bundle Vue even if your code imports Vue. The bundle will assume Vue is available on the host page as a global variable.

But it doesn't say that how to fix this problem when you want to use web-components inside another project.

Do you have any Idea?

2 Answers

In fact the statement you quote means that you do not need to use import Vue from 'vue'. Vue can be used as a global variable as it have been added by the script <script src="https://unpkg.com/vue"></script>.

Actually if you want to use components in another project built by vue-cli, firstly you should have a index.js (or any other name) , export components in that file like

export {default as Button} from './button/button'
export {default as ButtonGroup} from './button/button-group'
export {default as Cascader} from './cascader/cascader'

then change the 'scripts' in package.json 'vue-cli-service build --target wc --name foo ./src/index.js' you can copy the dist dirctory to the node_modules of the new project and then use it(but it is not recommend).you can use 'npm publish' it , and in your new project,use npm install it

Related