9

I am trying to import a single function to my Vue component. I've created a separated js file for my function:

randomId.js:

exports.randomId = () => //My function ...

In my Vue component, I've imported the Random js:

let randomId = require('../functions/randomId');
randomId();

but Webpack throws an error of "randomId is not a function". I tried to import the file using import syntax, but the error remains.

import randomId from '../functions/randomId';

Should I use some other methods for importing single functions? I'm relatively new to Webpack and JS6.

Negar
  • 649
  • 1
  • 6
  • 9
  • You may find [this article helpful](https://medium.com/@thejasonfile/a-simple-intro-to-javascript-imports-and-exports-389dd53c3fac) – craig_h Aug 09 '18 at 18:20

2 Answers2

13

Change your function module to properly use ES6 export:

export function randomId() { /*My function ...*/ }

And then use ES6 named import:

import { randomId } from '../functions/randomId';
connexo
  • 53,704
  • 14
  • 91
  • 128
1

If you want to use CommonJS, then in the file with your randomId function do the following:

function randomId() {
   ...
}

module.exports = randomId;

And then the let randomId = require('../functions/randomId'); in your Vue component will work.

José A. Zapata
  • 1,187
  • 1
  • 6
  • 12