I have a .js file in my project that imports an NPM package and has 2 functions that use that package:
//replacePaths.js
import {replaceInFile} from 'replace-in-file';
async function replace() {
const options = {
files: 'src/**/*.jsx',
from: 'dev/svgs/icons-main.svg',
to: 'staging/media/svgs/icons-main.svg',
};
try {
const results = await replaceInFile(options);
} catch (error) {
console.error('Error occurred:', error);
}
}
async function revert() {
const options = {
files: 'src/**/*.jsx',
from: 'staging/media/svgs/icons-main.svg',
to: 'dev/svgs/icons-main.svg',
};
try {
const results = await replaceInFile(options);
} catch (error) {
console.error('Error occurred:', error);
}
}
module.exports = {
replace,
revert
};
I want to be able to run these functions from the command line. I’ve Googled around and to do this it seems I just add the following to my package.json
file:
"scripts": {
...
"replace": "node replacePaths.js replace",
"revert" : "node replacePaths.js revert",
...
}
I the first of these in the command line as such: npm run replace
, but I got the error ReferenceError: module is not defined in ES module scope
.
Googling that, I changed the exports
part to:
export default replace;
export default revert;
and tried again. I didn’t get any errors, but instead just got the line node replacePaths.js replace
printed in the console.
I can run the functions by removing the export part and just having replace()
or revert()
on the JS file, but that’s not helpful to me if I want to have 2 functions on the same file.
Would anyone be able to point me in the right direction?
3
Answers
here’s the simplest answer – to run the function named on the command line
To run a different command depending on a command-line argument, your top-level code could be structured something like this:
Examples of running it: