Inject element-ui components into the element plus in main.js of vue 3

I am currently working on transitioning element-ui components to element-plus as part of my migration from vue 2 to vue 3. I have found that the documentation is lacking clarity on how to register components in vue 3 within the main.js file.

The error message I encounter is:

"export 'Tree' was not found in 'element-plus'
warning  in ./src/main.js
"export 'default' (imported as 'Vue') was not found in 'vue'

Below is a snippet of my main.js file:

import Vue, { createApp, h } from 'vue'
import Vue, { createApp, h } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import {
Button,
Select,
Option,
Dropdown,
TableColumn,
Checkbox,
Badge,
Divider,
Tag,
DropdownItem,
Pagination,
Table,
DropdownMenu,
Tree,
Tooltip,
} from 'element-plus'
import lang from 'element-plus/lib/locale/lang/en'
import locale from 'element-plus/lib/locale'



const getCookieConsent = localStorage.getItem('Cookie acceptance')

if (typeof getCookieConsent !== 'undefined' && getCookieConsent === 'true') {
FullStory.init({ orgId: '14C6AX' })
Vue.prototype.$FullStory = FullStory
}

locale.use(lang)

Vue.component(Tree.name, Tree)
Vue.component(Button.name, Button)
Vue.component(Divider.name, Divider)
Vue.component(Checkbox.name, Checkbox)
Vue.component(Pagination.name, Pagination)
Vue.component(Tag.name, Tag)
Vue.component(Badge.name, Badge)
Vue.component(Table.name, Table)
Vue.component(TableColumn.name, TableColumn)
Vue.component(Select.name, Select)
Vue.component(Dropdown.name, Dropdown)
Vue.component(DropdownItem.name, DropdownItem)
Vue.component(DropdownMenu.name, DropdownMenu)
Vue.component(Tooltip.name, Tooltip)
Vue.component(Option.name, Option)




createApp({
render: () => h(App)
}).use(router).use(store).mount('#app')

Answer №1

In Vue 3, registering components globally is not recommended. Instead, you should create a Vue app using the createApp method and register components for that specific app.

The element-plus documentation provides detailed instructions on how to import their components.

// main.js
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

// Create your Vue 3 app
const app = createApp(App)

// Option #1: Register all components (affects global bundle size)
app.use(ElementPlus, {
  // options
})

app.mount('#app')

If you prefer treeshaking, simply import and register components when needed:

// my-component.vue
// Option #2: Import and register components as needed
import { ElTree } from 'element-plus'

export default {
  components: {
    ElTree
  }
}

When importing components, it's suggested to use the prefix El, as they are exported in this format.

Answer №2

After updating my package, the previous code stopped working. Fortunately, I made some modifications and now it's functioning correctly. 1. In vite.config.js, delete the following:

      {
        libraryName: 'element-plus',
        libraryDirectory: 'es',
        style(name) {
          return `element-plus/theme-chalk/${name}.css`;
        },
      }
    ])

2. In main.js, replace the old use(component) with the following:

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus, {
  // options
})
app.component("ElSubmenu", ElMenu.SubMenu); // Registering ElSubmenu in this way seemed to be necessary

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React, manipulating the DOM by utilizing getElementById, and then attempting to swap out a node with a React Component

Is there a method to replace a DOM node with a ReactJS node? If so, how can it be achieved? const myComp = <span>hey</span> const elem = document.getElementById('video1') elem.parentNode.replaceChild(myComp, elem) What is the correc ...

Transform the angular code in order to execute innerHTML functions

function campform() { $.ajax({url: "{{ path('campform') }}", success: function(result){ $("#respuesta").html(result); }}); } I am having trouble with the angular code in the result I received. Can anyone provide guidance on how t ...

What is the correct way to retrieve store actions within a Vue test scenario?

I'm currently encountering a situation where my test is passing, but I'm unsure why I have to structure it in this particular way. Let me provide details of the test setup: describe("Photo Due", () => { const localVue = createLocal ...

Problem with declaring Javascript objects

Exploring the world of OOP for the first time, encountering a small challenge: const panel = { image : imgs[24], proportion : this.image.height / this.image.width, height : this.image.height - (scale), width : height / proportion, ...

How can I determine when a WebSocket connection is closed after a user exits the browser?

Incorporating HTML5 websocket and nodejs in my project has allowed me to develop a basic chat function. Thus far, everything is functioning as expected. However, I am faced with the challenge of determining how to identify if connected users have lost th ...

How to incorporate a phone number input with country code using HTML

Can anyone help me create a phone number input field with a country code included? I've tried a few methods but haven't had much success. Here is the code I've been working with: <div class="form-group "> <input class= ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

What is the best way to ensure that a regex pattern only matches if it begins with the user's

I am working on developing a search bar that identifies whether a brand is Indian or foreign. The data for this search bar is retrieved from a JSON file using the fetch API. Here's a snippet of the code: const matchList = document.querySelector(&ap ...

Issue encountered when setting a background image in Angular

When trying to add a background image and set it to cover the entire browser window, I encountered an issue where the image appeared very small and did not fully cover the background. As someone new to Angular, my understanding of how this process works i ...

Incorporating Facebook's iOS SDK for engaging with Comments through Connect

I am working on an iOS application where I intend to integrate Facebook Comments using Facebook Connect within a UIWebView. After conducting tests and researching articles, I believe that this integration will work well. My main query pertains to authent ...

How to send responses with parameters in Node.js for .js files

I am having some difficulty with my node.js http application. While I am able to properly handle GET requests, I am struggling to respond correctly to requests for files like foo.js?_param=1234. How should I handle files of this type which have parameters ...

Automatically fill AutoCompleteExtender with all options upon initial selection

I've been attempting to use autoCompleteExtender to display all possible options when a textbox is focused, but I haven't had any success so far. I tried adding an onfocus event in the textbox tag to call a JavaScript function that invokes the we ...

Are you able to combine createWebHashHistory and createWebHistory to generate Vue anchor hash links in the router?

I am currently working with vueJS3 and have a menu list setup like this: const menu = [ {ref: "../#home", name: "Home"}, {ref: "../areas", name: "Areas"}, {ref: "../#contact", name: "Contac ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...

"Utilize JavaScript to access and view the contents of a directory

My web app follows a standard folder structure which includes: css js img assets lib In addition, I have an index.html file. Within the assets folder, there are various plain text files. I am looking to use JavaScript to list the filenames in order to ...

A guide on extracting a URL from source tags using Cheerio/jQuery

I have been struggling to retrieve the first image with data-srcset attribute ("https://sample.img_1") using Cheerio. None of my previous attempts have been successful. My most recent attempt looks like this: $(".sample_picture [media='(max-width: 64 ...

Using $.bind() on SVG elements causes an error when a new SVG replaces the original one

I have a customized svg where elements are connected to user clicks and keyups. When a user modifies a text field on the website, it automatically updates the corresponding text element within the svg. Similarly, if the user edits the svg, the correspondin ...