最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to import a function to a Vue component? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Aug 9, 2018 at 18:15 NegarNegar 6591 gold badge6 silver badges10 bronze badges 1
  • You may find this article helpful – craig_h Commented Aug 9, 2018 at 18:20
Add a comment  | 

2 Answers 2

Reset to default 15

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';

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.

发布评论

评论列表(0)

  1. 暂无评论