Import a function in a .mjs script

287 Views Asked by At

Need some help with using a .mjs script and .js as well.

I have one script.mjs file that looks like this. Simplifying here (the script needs to be .mjs file)

import test from './test.js';

 test();

and test.js looks like this. Again simplifying here but it needs to be .js file:

const fs = require('fs');
const path = require('path');

const root = path.join(__dirname, '../../');
const statsPath = path.join(
    root,
    'somepath',
);

export function test() {
    const localBuildStat = JSON.parse(
        fs.readFileSync(statsPath, { encoding: 'utf8' }),
    );

    
    let assetSizes = {};
    
    const assets = localBuildStat.assets;
    assets.forEach((s) => {
       // do something here       
       }
    });
}

when I try to run the script.mjs file, I get this error:

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/XVdSz.png

How do you suggest I fix this to work? Thanks in advance

1

There are 1 best solutions below

0
Endless On

use module.exports in commonjs

module.exports = function test() {
  // ...
}