Home > Back-end >  How can I separate code in main.ts in Vue 3?
How can I separate code in main.ts in Vue 3?

Time:01-27

I'm new to Typescript and vue and I'm curious how I could pull out this code in my main.ts file. I'm just worried it's going to get really ugly eventually.

const app = createApp(App);

/* import the fontawesome core */
import { library } from '@fortawesome/fontawesome-svg-core'
/* import font awesome icon component */
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
/* import specific icons */
import { faHammer, faTruckPickup, faSortDown } from '@fortawesome/free-solid-svg-icons'
/* add icons to the library */
library.add(faHammer, faMagnifyingGlass, faSortDown)

app.component('font-awesome-icon', FontAwesomeIcon);

I would like my main.ts file to look something like this (doesn't have to be exact if there is a better way to do this).

import {addFontAwesomeIcons} from './fontAwesomeLibrary'

const app = createApp(app);

addFontAwesomeIcons(app); //this will use the app object and call library.add() and app.component('font-awesome-icon',FontAwesomeIcon);

So that my main.ts doesn't get polluted the more icons I have to add.

Any help would be appreciated

CodePudding user response:

fontAwesomeLibraryPlugin.ts

import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faHammer, faTruckPickup, faSortDown } from '@fortawesome/free-solid-svg-icons'
library.add(faHammer, faMagnifyingGlass, faSortDown)

export const falPlugin = {
  install(app) {
    app.component('font-awesome-icon', FontAwesomeIcon);
  }
}

main.ts

import { falPlugin } from './fontAwesomeLibraryPlugin'
const app = createApp(App);

app.use(falPlugin);
app.mount('#app');

Documented here.

  • Related