Importing and exporting JavaScript libraries

In this scenario, I have a collection of libraries that I've defined.

One such library is lib1.js:

export default {
    Func1() {
        return ...
    }
}

(and similarly for my other libraries in the same folder)

Now, I am importing these libraries into a main file called api.js, along with lib2 and lib3:

import './lib1';
import './lib2';
import './lib3';

Within my Vue component:

<script>
    import * as Api from '@/api/api';

    mounted() {
      Api.func1();
    }

</script>

A certain Mix error occurs indicating that the functions cannot be found:

"export 'Func1' (imported as 'Api') was not found in '@/api/api' .... 

I have confirmed that the pathing is correct because directly importing the libraries into the view works fine:

For example in Vue:



<script>
    import Lib1 from '@/api/lib1'
    import Lib2 from '@/api/lib2'
    import Lib3 from '@/api/lib3'

    mounted() {
      Lib1.func1();

      ...

    }

</script>

I'm puzzled by this situation. I simply want one "master" file to handle the importation of all my API functions instead of having to import each one individually.

Additional context: I am using Laraval 6 alongside Vue.

Answer №1

If you're looking to combine modules, I have demonstrated a method using StackBlitz as an example.
The reason your current approach isn't working is because you exported as `default` and when attempting to import `./lib1`, the module name is unknown.
Using `import * as Api` only works with multiple named exports, not just one default export.
It seems like you want to merge multiple libraries into one object. There are a few ways to accomplish this:

  1. Export named functions only (my preferred method):

lib1

export function Func1() {
  return ...;
}
export function Func2() {
  return ...;
}

then in the main file:

import * as lib1 from './lib1';

export default {
...lib1
}
  1. Use default export as shown in your example

lib1

export default {
 Func1() {},
 Func2() {}
}

then in the main file:

import lib1 from './lib1';

export default {
...lib1
}
  1. Export default but combined

lib1

export default {
 Func1() {},
 Func2() {}
}

then in the main file:

import lib1 from './lib1';

export default {
 lib1
}

However, in other files, you would need to use it like:

import Api from '@api/api';

Api.lib1.Func1()

Note: With your current setup, remember to use `import Api from '@api/api';` without the asterisk (*). You can also refer to this informative article on named imports versus default exports.

Answer №2

When it comes to organizing my code, all roads lead to index.js. I gather all my libraries in the same directory and export them from a single index.js file for easy importing.

index.js

import lib1 from './lib1';
import lib2 from './lib2';
import lib3 from './lib3';

export {
  lib1,
  lib2,
  lib3,
};

vue

import { lib1, lib2, lib3 } from '@/[directory with index.js]';

Alternatively, you could also try this approach:

import libs from '@/[directory with index.js]';

libs.lib1.someFunction();

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

Incorporating AngularJS into JSP for Seamless Integration

As part of our application upgrade, we are transitioning from JSP to AngularJS one module at a time. One challenge we face is transferring user data from JSP to AngularJS (specifically index.html). We aim for a smooth transition where invoking the Angular ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

Where can content-tag and main-tag be found in vue-virtual-scroller?

I've been trying to wrap my head around the vue virtual scroller. I couldn't help but notice in the demo that it utilizes a few HTML attributes... <virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" ...

Create rectangles on a canvas by parsing data from a JSON file

Hey there! I've been working with HTML5 canvas and I need some help drawing rectangles dynamically. Currently, I can draw on the canvas but I want to make it more flexible. x, y: These represent the coordinates of where the rectangle should be positi ...

What can I do to resolve the issue of my Navigation Bar being blocked by a Javascript map?

My navbar creates a dropdown menu when I hover over it, but the map generated with the script tag blocks it. Here is the current setup: // JavaScript Document //This will make the navigation bar responsive. function myFunction() { var x = document.ge ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...

Enhance your checkbox and radio components with React Higher Order Components (H

I'm in the process of designing my own custom checkbox and radio components to ensure reusability. This is what I have so far: import React, { Component } from 'react' export class Checkbox extends Component { render() { return ...

Tooltip displacement on the webpage

I'm encountering an issue with the placement of tooltips in my buttons. The problem is specifically with the last, right-most button tooltip - it seems to be displaying on the left side of the page instead of below the button as intended. Check out t ...

Ways to halt the setInterval function after executing a specific function within it

Currently, I have a condition in place to verify if I am on a specific URL. If this condition is true, the setInterval() function will begin checking for a particular element on the webpage. Once the element is located, a designated function will be exec ...

Deactivate any days occurring prior to or following the specified dates

I need assistance restricting the user to choose dates within a specific range using react day picker. Dates outside this range should be disabled to prevent selection. Below is my DateRange component that receives date values as strings like 2022-07-15 th ...

Switch up the image source without altering the dimensions

Looking to modify the src attribute of an image $('.bact').attr('src', '00.jpg'); 00.jpg has dimensions that are different from the original. Is there a way to change the src, while keeping the original image width and hei ...

Tips for implementing HTML5 validation followed by automatic redirection to a different page

I'm new to web development and struggling with how to make a button both validate inputs and redirect to another page. Using the onclick = "" function, I can validate inputs like emails and telephone numbers, but I'm having trouble making it so t ...

Utilizing helper functions in Node based on their specific types

In my helper module, I have different files like content, user, etc. These files define various helpers that can be used in the router. Below is the code for the router: router.js var helper = require("./helper"); function index(response) { response ...

What are the steps to utilize a public or internal class in JavaScript within an Asp.Net environment?

I've been developing an asp.net web application and I'm looking to incorporate a class in JavaScript. In the asps.cs file, using a class like this is straightforward: ABC obj = new ABC(); obj.name = "John"; Is it possible to use a class in a si ...

A step-by-step guide on installing an npm package from the GitHub registry

Uncertain of the process for installing a package from the GitHub registry that relies on dependencies from the public npm registry. Attempted solution: npm_config_registry=https://npm.pkg.github.com npx @octopol/development This method failed due to som ...

Triggering an id import via ajax when changes occur

I've come across a small script that I didn't create myself, and I want to make some modifications to it, but I've hit a roadblock. The script features two select options: one for selecting a state and the other for selecting a city. When a ...

Is it possible to disregard JQMIGRATE warnings for AngularJS v1.4.5 and proceed with upgrading AngularJS?

I currently have jquery 2.2.4 and AngularJS v1.4.5 integrated into my website. After setting up jquery-migrate-1.4.1, I encountered the following warning: JQMIGRATE: jQuery.fn.attr('selected') might use property instead of attribute The issue s ...

Retrieving multiple lines of text from the database and populating a TextArea

I am encountering an issue with multi line text saved in a MySql database as VARCHAR 255. When I retrieve and process it using the nl2br PHP function, it displays correctly (with multiple lines). However, when I retrieve the multi line text from the databa ...

PHP Survey and Principles

I am new to PHP and I am attempting to create a poll where each answer holds a value ranging from 0 to 3. My goal is to display a different message based on the total sum of these values when the user submits their responses. For example, if the total sum ...