What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable to export two vue directives in the same index.js file.

export default Vue.directive('directive1', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

export default Vue.directive('directive2', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

Answer №1

If you are looking to export two defaults, keep in mind that using a default allows you to easily retrieve the value with a simple import statement like

import MyPack from 'path/to/package'
. Make sure to export constants and destructure when importing to ensure smooth functionality. For more information, check out this helpful resource here

In your package:

export const vD1 = Vue.directive('directive1', {
  ...
})

export const vD2 = Vue.directive('directive2', {
  ...
})

During your import process:

import { vD1, vD2 } from 'path/to/package';

Answer №2

Refer to the Vue Guide: Writing one plugin for guidance on developing directives and allowing users to activate specific directives using the 2nd parameter=options.

For example, consider the demo below (assuming exporting myDirectives and enabling only directive1):

let myDirectives = {}
let _defaultDirectives = ['directive1', 'directive2']
myDirectives.directive1 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive1', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.directive2 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive2', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.install = function (Vue, options) {
  let selectedDirectives = (options && options.directives) || _defaultDirectives
  selectedDirectives.forEach((directive) => 
    Vue.directive(directive, this[directive])
    // this[directive + 'Definition'] = Vue.directive(directive, this[directive])
  )
}

// export default myDirectives

// Vue.use(myDirectives) // default option is register both directive1 and directive 2
Vue.use(myDirectives, {directives: ['directive1'] }) // register directive1 only

// console.log('Definition', myDirectives.directive1Definition, myDirectives.directive2Definition)

new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span v-directive1></span>
  <span v-directive2></span>
</div>

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

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

Set up npm to run grunt

I am trying to install grunt but having trouble with npm. I followed the instructions at http://gruntjs.com/getting-started However, when I tried running the command: $ npm install -g grunt-cli -bash: npm: command not found Any help would be appreciate ...

Automating Deployment: Deploying React App on Development Domain with Plesk Server

Currently, I am in the process of developing multiple React apps and it would be great to have the ability to continuously deploy them from a GitHub repository to a development domain for clients to access. To achieve this, I set up a webhook through GitHu ...

Display a list of dates within a specified range using the ng

Utilizing the ng-repeat directive to connect data with a filter for name search: <div ng-repeat='myoldrecs in myoldrec | filter:q as results '>......</div> $scope.myoldrec = [{name:ccc,date:13-02-2016},{name:ddd,date:14-02-2016}]; &l ...

Step by step guide on inserting a message (memo/sticky note) onto an HTML page

Wondering how to accomplish this: I've designed an HTML5 homepage and I'm looking to display a message to visitors, such as "Dear visitor, I am currently on vacation from....", in the form of a memo or sticky note positioned in the top right cor ...

Unexplained disappearance of div element in Vue Router's Navbar

I have been working on integrating a Vue Router into my navbar and everything seemed to be going well. You can check out the code here. The navigation menu I created works perfectly, allowing users to navigate between the home template and about template w ...

Clicking the React Todo Delete Button instantly clears out all tasks on the list

I am dealing with 2 files: App.js import React, { Component } from 'react'; import './App.css'; import ToDo from './components/ToDo.js'; class App extends Component { constru ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Having issues with my AngularJS application not updating as expected

After creating a custom service to store all search parameters, I can easily access them from any part of my code. This ensures that the search parameters are always accurate. Below is the definition of the custom service: App.factory('filterService& ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

Unlocking the nested v-for in Vuejs to access id and submit using axios

I am currently working on developing an application that utilizes a typeorm backend and a Vue.js frontend. This app is designed to collect customer data through surveys. For this purpose, I retrieve data from my backend using an axios get request, and I i ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

Data structures of advanced complexity within HTML data attributes

I am delighted by the existence of the html5 data attribute. It's great to be able to input a plain string into html attributes and retrieve them using jquery. However, wouldn't it be wonderful to have more than just a basic string? Is there a ...

What a great method to execute a button click within the same button click using jQuery!

Here's an example of code that attempts to make an ajax call when a user clicks a button. If the ajax call fails, the button should be reclicked. I've tried this code below, but it doesn't seem to work. $("#click_me").click(function(){ ...

When clicking on the text areas, the Twitter-Bootstrap drop-down login automatically closes

Greetings! I am currently working on my first website design using JQuery. My project includes a dropdown login box created with Twitter-Bootstrap. Unfortunately, I'm facing some challenges with the JQuery script that controls the behavior of the logi ...

Utilizing Vue's string-based class binding feature?

Can Vue class binding work with strings? For example: <div :class={open: target == 'myString'}></div> var app = new Vue({ target: null }) It works when I don't use quotes <div :class={open: target == myString}></div ...

What is the process for deprecating an npm package that has been published to the GitHub package registry?

I have a confidential package published on the GitHub package registry. I am looking to mark it as deprecated. Attempted to execute the following command: npm deprecate --verbose @test-engineering/test-roles "This package has been deprecated and suppl ...

Difficulties arise when attempting to install nodejs on linux using the npm install nodejs command

While attempting to execute... npm install nodejs I encounter the subsequent issue: npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email prot ...

Transmit and receive information between Javascript and Node.js through Express framework

Currently, I am utilizing the Express platform along with the Twilio Node.js SMS API and JavaScript to send text messages to my users. However, I am facing an issue in sending data through GET variables on the front-end and capturing those values with node ...

Using HTTPS, you can access Flask from AJAX

I have encountered numerous inquiries concerning this issue, but none have proven effective for me. I recently switched my domain from HTTP to HTTPS. Everything was functioning properly on HTTP. The main issue lies in the fact that my javascript and flask ...