I have developed a basic component using TypeScript that relies on d3 as a dependency. My goal is to make this component available on npm and adaptable for use as a global script, a commonJS module, or a TypeScript module. The structure of the component is outlined below:
/// <reference types="d3" />
class MyAwesomeComponent {
data(data: IMyDataFormat) {
// set data, etc.
}
render() {
// do stuff with d3
}
}
interface IMyDataFormat {
// keys/types
}
The current configuration of my tsconfig.json
file is as follows:
{
"compilerOptions": {
"module": "none",
"target": "es5",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"declaration": true,
"outFile": "./dist/index.js",
"sourceMap": true
},
"include": [
"./src/**/*.ts"
]
}
Upon running tsc
with this setup, I obtain a file that functions effectively in the global context, making it usable by consumers like so:
<script src="./d3.js"></script>
<script src="./my-awesome-component.js"></script>
<script>
var chart = new MyAwesomeComponent();
chart.data([/* ... */]);
chart.render();
</script>
How can I configure my project (e.g., through alternative tsconfig files or minor adjustments to source files) to ensure that it can also be consumed in a commonJS environment (e.g., webpack or browserify), as well as in a TypeScript project setting?
For the commonJS environment, the following should work:
const MyAwesomeComponent = require('my-awesome-component');
// alternatively:
const MyAwesomeComponent = require('my-awesome-component').MyAwesomeComponent;
And for the TypeScript environment:
import {MyAwesomeComponent, IMyDataFormat} from 'my-awesome-component';
Thank you!