If you're thinking of deploying a TypeScript package to NPM, you should be considering Preconstruct. It's incredibly easy to set up and it handles so many things for you.
Let's get started. We have a simple index source file, which just is inside src.
export const hello = () => {}
And we've got our package.json here, which has a basic name, "matt-preconstruct-example". This is not set up at all for deploying to NPM.
{
"name": "matt-preconstruct-example",
"version": "1.0.0",
"main": "index.js",
"author": "Matt Pocock",
"license": "MIT",
"devDependencies": {
"typescript": "^4.6.4"
}
}
Let's see how quick it can go. Run the following command in your terminal.
yarn add -D @preconstruct/cli
This is going to install a CLI that handles our building along with a bunch of other stuff.
And now we run this:
And Preconstruct is there because we've installed the CLI. You'll notice here in our package.json, that it's added dist/matt-preconstruct-example.cjs.js into our main.
{
"name": "matt-preconstruct-example",
"version": "1.0.0",
"main": "dist/matt-preconstruct-example.cjs.js",
"author": "Matt Pocock",
"license": "MIT",
"devDependencies": {
"@preconstruct/cli": "^2.1.5",
"typescript": "^4.6.4"
}
}
So we don't even need to think about our main. If we want to add bundling for ESM, we can just add "module": true, and run yarn preconstruct fix again, and it will go in and add the ESM version.
Now we can run the following:
While this is running I'll go ahead and add that build command to my scripts in my package.json
{
"name": "matt-preconstruct-example",
"version": "1.0.0",
"main": "dist/matt-preconstruct-example.cjs.js",
"author": "Matt Pocock",
"license": "MIT",
"scripts": {
"build": "yarn preconstruct build"
},
"devDependencies": {
"@preconstruct/cli": "^2.1.5",
"typescript": "^4.6.4"
}
}
And now we've got a dist file with all of the correct stuff in there. We can just ignore it for now.
And we've got cgs.d.ts. We've got all of our declaration files properly exported. We've got everything working for ESM as well if we want it. It just gives you everything out of the box.
And from here, you could just run yarn publish or npm publish, send this up to the cloud, and it'll be ready for you to use in any of your apps.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.