The error "Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0__.writeSomething is not a function" occurs in Vue.js when trying to use a function from a local

Trying to incorporate a local JS file into a single Vue component using a vue-CLI scaffolded application (ver 3.8.2).

Below are the pertinent code snippets:

/path/to/app-vue/src/components/HelloWorld.vue

<template>
  <div class="hello">
    <Module1/>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import Module1 from './Module1.vue';

@Component({
  components: {
    Module1,
  }
})
export default class HelloWorld extends Vue {
  @Prop() private msg!: string;
}

</script>

<style scoped>
</style>

/path/to/vue-app/src/components/Module1.vue

<template>
    <div class="module1">
        Module2
    </div>
</template>

<script>
import { Component, Prop, Vue } from 'vue-property-decorator';
import Module2 from './Module2.vue';

@Component({
  components: {
    Module2,
  },
})
export default class Module1 extends Vue {
}
</script>

/path/to/vue-app/Module2.vue

<template>
    <div id='demo'>
    </div>
</template>

<script>
import foo from '../assets/js/foo';

foo.writeSomething('#demo');
</script>

/path/to/vue-app/src/assets/js/foo.js

function writeSomething(el) {
  elem = window.document.getElementById(el);
  elem.innerHTML = 'Hello World!';
}

export default {
    writeSomething
}

Upon running npm run serve and visiting '/', console errors are displayed:

"export 'default' (imported as 'mod') was not found in '-!../../node_modules/cache-loader/dist/cjs.js??ref--12-0!../../node_modules/babel-loader/lib/index.js!../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../node_modules/vue-loader/lib/index.js??vue-loader-options!./Module2.vue?vue&type=script&lang=js&'

DevTools console reports:

Uncaught TypeError: _assets_js_foo__WEBPACK_IMPORTED_MODULE_0__.writeSomething is not a function
    at eval (Module2.vue?df9f:9)
   ...

How can I successfully load and utilize functions from local javascript files within a Single File Component?

Answer №1

To ensure proper functionality, you must explicitly use the export keyword when defining a function and then import it by referencing its name.

Utilizing Modules in Vue Component

import { writeSomething } from '../assets/js/foo.js';
writeSomething('#demo');

export default { ...

Content of foo.js Module

export function writeSomething(el) {
  elem = window.document.getElementById(el);
  elem.innerHTML = 'Hello World!';
}

For TypeScript Users: Ensure that JavaScript modules can be imported properly

An alternative approach is to export a default module as well

function writeSomething(el) {
  elem = window.document.getElementById(el);
  elem.innerHTML = 'Hello World!';
}


export default {
    writeSomething
}

To import and utilize the default module, follow these steps:

import foo from '../assets/foo.js';

// ...
foo.writeSomething('#demo');

Answer №2

To ensure clarity, it is recommended to specify a name when using export default, as shown below:

export default writeSomething;

Differences between Named Exports and Default Exports

  • Named Exports allow for the exporting of multiple values.
  • When using Named Exports, the exported name must be used when importing.

    Default Exports, on the other hand,

  • Allow for the exporting of a single value only.
  • Any name can be used when importing with Default Exports.

For further information on Named Export and Default Export, please visit this link

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

What is the best way to loop through an array in vue, creating a new row for each item of data?

Utilizing the Axios library, I fetch streaming data which returns a JSON object containing sensor information such as {"Temperature":"56"}. Upon receiving this data, I attempt to populate rows in my Vue template by assigning the response.data to an array. ...

Issues with hover styles and transitions not being correctly applied to newly appended elements in Firefox

Utilizing an SVG as an interactive floor plan, I have implemented a feature where hovering over different areas on the floor plan (<g> elements) causes them to expand and float above other areas. The element scaling is triggered by CSS, but I use jQu ...

Checking for IE-9 compatibility during end-to-end testing with the use of phantomJS

In order to test my application for compatibility with IE-9, I am using a combination of PhantomJS (headless end-to-end testing), Selenium WebDriver, and Grunt (task runner). It is crucial that the application functions flawlessly on IE-9. Headless testi ...

Clicking on a radio button will instantly update a specific section of the webpage

Is there a way to implement radio buttons with specific filters that can dynamically change content on a website without the need for a full page refresh? Picture having radio buttons on the left side of the navigation, with a table on the right that smoo ...

Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly ...

Transforming the time from the local timezone to Coordinated Universal Time (

I need help figuring out how to convert a Javascript date object to UTC, assuming a timezone like America/New_York: 2019-01-04T00:00:00.000Z The desired result is to convert this to a date object in UTC. 2019-01-04T05:00:00.000Z const timezone = ' ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

Exploring the benefits of leveraging Express with SSL security features

I recently acquired a Comodo SSL certificate for setting up an SSL server with express. The certificates I have include: AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt mysite.com.key mysite.com.csr mysite_co ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Can a Javascript binary search only match on values greater or equal?

When searching, this code will find the closest match. Usually, the closest match's x value is smaller than the target.x. Is there a way to find the closest match where match.x is greater than or equal to the target.x value and match.y is the nearest ...

Tips for choosing the initial link within a parent list entry

I am working with a jQuery accordion and have a specific need to remove the href attribute from the parent li element without affecting its children. This task requires precision in targeting only the parent li. var parent = $("#quicklaunch ul > li:has ...

The administrator user assigns a user value in the authentication context, but that value remains hidden from the component where it was originally set

The authentication feature: import React, { useState } from 'react'; let selectedUserByAdmin = ''; const AuthContext = React.createContext({ setSelectedUserByAdmin: () => {}, selectedUserByAdmin, }); export const AuthContextPro ...

Setting up RTL (Right to Left) functionality in Material UI version 5 - A Step-by-Step Guide

After updating my app to version 5 of Material-UI from version 4, I noticed that the RTL support is no longer functioning. I carefully followed the instructions in the documentation: https://mui.com/guides/right-to-left/ The current outcome is that the ...

Loopback Model Property Somehow Resurrected After Deletion

Within my function, I am working with an object called 'ctx.instance' that contains various properties: firstName: 'Ron', lastName: 'Santo', minor: true, accepted: false, emailChanged: false, organizationId: 00000000000000000 ...

Managing numerous HTTP requests and providing the outcome through Angular and Rxjs

Currently, I am facing a challenge with sending GET requests for a large number of URLs (50 of them) to the Spotify server and then returning their results in a single Observable/array/object. This is the code snippet I have come up with: curatedTopArti ...

Choose and display a specific set of data from a JSON array

On this particular link, there is an array containing 100 sets of values. I have exhausted my brain trying to figure out how to access and display the "percent_change_24h" value for only the first 0..10 sets in order to calculate the average. <script&g ...

another way to achieve blinking effect

Currently I am working on developing a calculator application and require a blinking function to improve user experience. The idea is to have a "|" symbol blink after the user inputs each number. I found a solution for Firefox and Opera using the following ...

Does anyone have insight on which JavaScript library is being utilized in this context?

While perusing an interesting article, I came across an image that caught my attention. Clicking on it revealed a unique way to view the full size. I am curious if anyone knows which JavaScript library was used for this effect. You can find the article her ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...