I built a TypeScript module and pushed it to GitHub. I now want to use this module inside my MyApp
as a dependency which is also written in TypeScript. The package is registered in my MyApp/package.json
:
"dependencies": {
"foo": "github:organization-xyz/foo",
}
I added a command build-ts
to create the corresponding JavaScript
bindings inside my foo module foo/package.json
:
"scripts": {
"build-ts": "tsc"
...
},
Of course, this command is not executed when I call npm i
on my main application. How would I properly prepare my module foo
in order to import it successfully inside my app?
CodePudding user response:
Put your build command in a package.json
prepare
script.
For example:
"scripts": {
"prepare": "npm run build-ts"
"build-ts": "tsc"
...
},
prepare
is one of the
Life Cycle Scripts that are automatically run by npm in certain situations. One of the situations is when package dependencies are installed, as stated in the npm-install docs:
If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.
Since the prepare script is also run before publishing, be sure configure your package.json
to not publish the build artifacts.
Since you mentioned that you are publishing it on GitHub, here is some more info specific to that case:
- Installing and Building an NPM Package from Github - Jim Nielsen’s Blog - This one specifically discuses the use of npm
prepare
scripts. - Install NPM Packages from GitHub | Pluralsight
That said...
...if the build does not have dependencies on the install target (e.g. cpu-architecture), standard practice is to transpile your Typescript into Javascript before publishing. Pretty much everyone does this, including the makers of Typescript. But I'm not going to make the case here...