Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a variable form my app into package.json?

I know this sounds as easy as using globals, but I'm not so sure.

Here's my case:

  • I have multiple files within /src directory of my React app, let's call them src/a.js, src/b.js,
  • every single of these files exports one object which I then use within my app:

./src/a.js:

export default {
  filename: 'a',
  foo: 'bar',
};

./src/b.js:

export default {
  filename: 'b',
  foo: 'bar',
  blah: 'hah',
};

Now I have a command to check whether or not structure of objects within these files match (they are being changed by many developers multiple times a day), so when I do npm check in terminal it will return false for above input, because blah does not exist within two files.

My package.json looks like this:

"scripts": {
  "check": "node check.js runCheck",
  /.../
}

My question is: how the heck do I load these variables to compare them in package.json?

I have a file called:

./check.js:

function check(files) {
 // checking files there
};

module.exports.check = check;

Approach #1 - imports

This is a build file, not part of the application itself, so when I try to do:

./check.js:

import a from './src/a';
import b from './src/b';

I'm getting:

SyntaxError: Cannot use import statement outside a module.

Approach #2 - require

This is going to cause trouble, because I'm using imports, not modules within my app, therefore doing:

./check.js:

const a = require('./src/a');
const b = require('./src/b');

Returns:

Error: Cannot find module './src/a'.

Of course I can't do module.exports within the a.js/b.js files, because they're part of my app and they should use exports, I've tried using both export and module.exports, but it does not work as well and looks shitty.

How do I tackle this? Should I load the files using some file loader, parse it as JSON an then compare? Or maybe there's an easier way?

like image 810
Wordpressor Avatar asked Dec 20 '25 09:12

Wordpressor


1 Answers

You'll need to use something like esm (https://github.com/standard-things/esm) to run node with module support.

It should be as simple as:

npm install esm

Then update your package script to be:

"check": "node -r esm check.js runCheck",

Edit Btw, a very clear and well structured question.

like image 52
Chris Avatar answered Dec 21 '25 21:12

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!