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

I wrote a simple component in typescript that has a dependency on d3. I would like to publish this component on npm and use it as a global, commonjs module or 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
}

Currently, my file is tsconfig.jsonas follows:

{
  "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 tscwith this configuration, I get a file that works in a global context, so this will work for the consumer:

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

(, tsconfig ..), commonJS (, webpack ), typescript ?

commonJS:

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

typescript:

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

!

+4
1

npmjs.org.

  • stackoverflow-47210046.
  • GitHub source.
  • , :
    • , "dom" tsconfig.json, . ( , , d3 TS.)
    • "main": "lib/index" package.json. , .
    • Adde "typings": "lib/index" package.json.
    • lib ​​ , npmjs.org.
    • ts-node, tsc .
    • , npm run test -- -w.
    • tsc , npm run build -- -w.

, , - , GitHub.

.

+1

Source: https://habr.com/ru/post/1689018/


All Articles