简体   繁体   中英

import.meta.url giving error 'unexpected token' with mocha tests

I have a javascript project where I have a data.js file which is reading some data from a.json file present in project root/src directory. In my mocha test I am importing data.js. During the test run it gives the problem with 'import.meta.url' which is present in data.js stating unexpected token.

SyntaxError: E:/Project/src/data.js: Unexpected token (4:48)
  2 | import path from 'path';
  3 |
> 4 | const _dirname = path.dirname(decodeURI(new URL(import.meta.url).pathname)).substring(1);
    |                                                 ^                                           
       const dataFile= path.join(__dirname, 'files', 'data.json');

I know how to resolve this. If I comment line#4, test runs fine. But then I get into problem when running the app with node command as 'node app.js' It starts giving error as below. To resolve this I can again uncomment line # 4, which make the app runs fine, but start failing the test when run with 'npm run test'. I am getting into catch22. Can somebody help please?

(node:1588) ExperimentalWarning: The ESM module loader is experimental.
file:///E:/Project/src/data.js:15
const dataFile = path.join(__dirname, 'files', 'data.json');
                                ^

ReferenceError: __dirname is not defined
    at file:///E:/Project/src/data.js:15:33

I could find a way to resolve this issue by using 'app-root-path' library. https://www.npmjs.com/package/app-root-path

Other than this no other workaround helped.

Finally this is how I built the path, and it works for both while running the app as well as tests!

import appRoot from 'app-root-path';

const filePath = appRoot.resolve('/src/files/data.json');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM