Home > Software design >  how to export function so it is accessible with import and require?
how to export function so it is accessible with import and require?

Time:11-03

I want to export a function so it is accessible for testing with mocha and to be used in html

if I export like below, mocha return SyntaxError: Unexpected token 'export'

//query.js
export function proses (data)  {
...}

if I export it like below, it would return error proses undefined

//query.js
function proses (data)  {
...}
module.exports = proses;

this is how I imported them on index.js and on test.js

//index.js
import { proses } from '../public/static/query.js'

and on test.js

//test.js
var proses = require('../public/static/query');

CodePudding user response:

I think it is best you choose either CommonJs or ESM and stick to that. For CommonJs:

//query.js
function proses (data)  {
...}

module.exports = proses

And when importing:

const proses = require('../public/static/query');
  • Related