A TypeScript transformer for use with ttypescript that will append the JS extension to all relative imports that have no extension.
npm install @evg656e/typescript-transformer-append-js-extensionimport { Foo } from './foo', the browser will try to fetch a file at the path http://my-domain/path/foo. Unless you configure your HTTP server to serve up JS files when no extension is provided, the web server will likely not find any file at that path because the actual file lives at http://my-domain/path/foo.js. One potential solution to this problem is to write your TS like import { Foo } from './foo.js'. TypeScript is clever enough that it will realize that you _really_ meant foo.ts during compilation, and it will successfully find type information. However, ts-node is not clever enough to handle these faux paths so if you want a library that works in either ts-node or browser you are out of luck.
.js extension as a compiler option, but for the time being we'll have to do it ourself.
typescript, ttypescript, and this transformer into your project if you don't already have them.
npm install --save-dev typescript
npm install --save-dev ttypescript
npm install --save-dev @evg656e/typescript-transformer-append-js-extension
`
1. Add the transformer to your es2015 module tsconfig-es.json (or whatever tsconfig.json you are using to build es2015 modules)
`json
// tsconfig-es.json
{
"compilerOptions": {
"module": "es2015",
"plugins": [
{
"transform": "@evg656e/typescript-transformer-append-js-extension/output/index.js",
"after": true,
}
]
},
}
`
1. Write some typescript with normal imports
`typescript
// foo.ts
export function foo() { console.log('foo') }
`
`typescript
// index.ts
import { foo } from './foo'
foo()
`
1. Compile using ttsc
`
npx ttsc --project tsconfig-es.json
`
Configuration
By default, only relative paths are transformed. You can force the transformation of absolute paths using forceInclude option, which accepts an array of strings of RegExp patterns, e.g.:
`json
// tsconfig-es.json
{
"compilerOptions": {
"module": "es2015",
"plugins": [
{
"transform": "@evg656e/typescript-transformer-append-js-extension/output/index.js",
"after": true,
"forceInclude": [
"^lodash/.*"
],
}
]
},
}
`
Additionaly you can specify forceExclude option, which specifies paths that should be skipped when resolving forceInclude option:
`json
// tsconfig-es.json
{
"compilerOptions": {
"module": "es2015",
"plugins": [
{
"transform": "@evg656e/typescript-transformer-append-js-extension/output/index.js",
"after": true,
"forceInclude": [
"^lodash/.*"
],
"forceExclude": [
"^lodash/isRegExp$"
]
}
]
},
}
``