Make package.json scripts work on both macOS and Windows

25 Views Asked by At

I am using Jasmine test suite to run tests in my codebase.

It works great on my Mac. the command is

open SpecRunner.html

Here's the full scripts object:

"scripts": {
    "start": "npm install",
    "test:local": "open SpecRunner.html",
    "test:remote": "karma start"
  },

The problem I am having is that my friend told me npm run test:local isn't working on his Windows machine. I believe the correct command in start SpecRunner.html.

What's the best way to make this compatible across operating systems?

ChatGPT recommended this solution:

"scripts": {
  "open-spec": "cross-env OS_TYPE=$(uname) npm run open-spec-$(uname | tr '[:upper:]' '[:lower:]')",
  "open-spec-darwin": "open SpecRunner.html",
  "open-spec-linux": "xdg-open SpecRunner.html",
  "open-spec-win32": "start SpecRunner.html"
}

I'd prefer a simple way to combine the command into one script though. Is that possible? I don't have a Windows machine to test myself! Thank you!

2

There are 2 best solutions below

0
Pedro Caires On BEST ANSWER

This has already being answered here before. Take a look at this question here: npm package.json OS specific script.

I believe the second answer is what you want. Wrapping it with some node if else. https://stackoverflow.com/a/45082999/10880357.

But I like the first one better (which is similar as GPT), looks like you and your friend are starting a project or something. It will not hurt to type : test:mac or test:windows

My advice for you: Keep focused on what is going to bring your value.

0
Mr. Polywhirl On

The npm package open:10.0.4 provides a cross-platform solution to this.

First, install the package:

npm i -D open-cli

Then update your script:

{
  "scripts": {
    "test:local": "open-cli SpecRunner.html",
  }
}