Home > Back-end >  npm "bin" scripts executing on import
npm "bin" scripts executing on import

Time:10-05

I have a TypeScript 4.8.4 library that's being packaged with npm. In my package.json I have a "bin" section that includes some utility scripts that are helpful for consumers of the package.

  "bin": {
    "generate-docs": "./docs/docs.py",
    "configure-this-and-that": "lib/configure-this-and-that.js",
    "register-things": "lib/data/register-things.js"
  }

The trouble is that even the simplest usage triggers all those scripts to execute when this package is imported. This happened when I updated to TypeScript 4.8. Previously this wasn't happening with TS 3.7.

import { Anything } from 'my-package-from-above';

// This causes the files in "bin" above to run
const anything = new Anything();
console.log('Done');

Is this different behavior in TS4? Is it something with the package.json setup?

Edit The class that's getting executed when imported looks like this. Is there something in the way it's written that could be doing it?

#!/usr/bin/env node
import { DeployUtility } from './deploy-utility';
const deployUtility = new DeployUtility();
deployUtility.configureDomainMapping().then(data => {
  return data;
});

The body of this class is getting executed whenever anything imports the containing package (even if it's not importing this class above).

CodePudding user response:

Figured out what the issue was, the scripts were being included in the index.ts file. Including the *.ts files that are used to generate the *.js files in the "bin" section of the package.json in the index.ts exports causes those files to be executed anytime the package is referenced.

The solution was to remove the exports that had a construct like the configureDomainMapping example above

Remove this (and any like it) from index.ts

export * from './configure-domain';

  • Related