0

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

AlreadyLost
  • 767
  • 2
  • 13
  • 28
  • 2
    I would just rip the bandage off and use ESM in the entire project. and skip all the dual hazzard problems. and also add type=module in package.json and only use .js – Endless Sep 13 '22 at 13:38

1 Answers1

2

use module.exports in commonjs

module.exports = function test() {
  // ...
}
Endless
  • 34,080
  • 13
  • 108
  • 131