How to publish a component written in typescript consumable as a global, commonjs, or typescript module

Viewed 248

I have written a simple component in typescript which has a dependency on d3. I would like to publish this component on npm and have it be usable as a global, a commonjs module, or a typescript module. The component looks something like this:

/// <reference types="d3" />
class MyAwesomeComponent {
  data(data: IMyDataFormat) {
    // set data, etc.
  }
  render() {
    // do stuff with d3
  }
}
interface IMyDataFormat {
  // keys/types
}

My tsconfig.json file currently looks like this:

{
  "compilerOptions": {
    "module": "none",
    "target": "es5",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "declaration": true,
    "outFile": "./dist/index.js",
    "sourceMap": true
  },
  "include": [
    "./src/**/*.ts"
  ]
}

When I run tsc with this config, I get a file which works in the global context, so this would work for a consumer:

<script src="./d3.js"></script>
<script src="./my-awesome-component.js"></script>
<script>
  var chart = new MyAwesomeComponent();
  chart.data([/* ... */]);
  chart.render();
</script>

How do I set up my project (e.g. with alternate tsconfig files or small changes to the source files etc) so that it is consumable in a commonJS environment (i.e. webpack or browserify), as well as in a typescript project environment?

Here is what I am expecting to work for the commonJS environment:

const MyAwesomeComponent = require('my-awesome-component');
// this would also be fine:
const MyAwesomeComponent = require('my-awesome-component').MyAwesomeComponent;

Here is what I am expecting to work for the TypeScript environment:

import {MyAwesomeComponent, IMyDataFormat} from 'my-awesome-component';

Thanks!

1 Answers

I have published a boilerplate example to npmjs.org.

  • The package is called stackoverflow-47210046.
  • I have also created a GitHub repository with the source.
  • The main documentation with some steps are available there but here a few remarks too:
    • Make sure you have added "dom" to the libraries in the tsconfig.json to include them during the compilation. (This is not required in general, but the question was about consuming d3 in a boilerplate TS package.)
    • Add "main": "lib/index" to the package.json. You can see, it points to the compiled output and has no file extension.
    • Adde "typings": "lib/index" to the package.json.
    • Although the lib output folder is not added to version control, that will be available on npmjs.org.
    • The tests will be executed with ts-node so the tsc compilation can be omitted.
    • If you want to run your test in watch mode, execute npm run test -- -w.
    • If you want to run your tsc compiler in watch mode, execute npm run build -- -w.

I hope this helps, if you have any questions, just post it here, or submit a new issue on GitHub.

Cheers.

Related