├── .eslintrc.cjs ├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── Lib.ts ├── README.md ├── jest.config.cjs ├── package-lock.json ├── package.json ├── run.ts ├── test.ts └── tsconfig.json /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | ecmaVersion: 2019, 5 | sourceType: 'module', 6 | }, 7 | plugins: [ 8 | '@typescript-eslint', 9 | 'jest', 10 | ], 11 | env: { 12 | node: true, // for `console` 13 | 'jest/globals': true, // describe, test, expect 14 | }, 15 | extends: [ 16 | 'eslint:recommended', 17 | 'plugin:@typescript-eslint/recommended', 18 | ], 19 | rules: { 20 | indent: ['error', 2], 21 | semi: ['error', 'always'], 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests on Node 13 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | # Syntax: https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions 5 | 6 | name: CI 7 | 8 | on: [push, pull_request] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | node-version: [13.x, 14.x] 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Use Node.js ${{ matrix.node-version }} 22 | uses: actions/setup-node@v1 23 | with: 24 | node-version: ${{ matrix.node-version }} 25 | 26 | # Install dependencies 27 | - run: npm ci 28 | 29 | - name: Run tests 30 | run: npm t 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.js 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Dan Dascalescu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lib.ts: -------------------------------------------------------------------------------- 1 | export class Lib { 2 | run(): void { 3 | // Make sure optional chaining works - either by `tsc` transpiling it, or by node running it under a flag 4 | const a = { 5 | b: { 6 | c: 'foo' 7 | } 8 | }; 9 | a.b?.c && console.log('Own module imported successfully'); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Modern TypeScript project template 2 | 3 | Minimalistic example of configuring TypeScript and Node to: 4 | * emit modern ES modules code 5 | * import modules that use Node built-ins 6 | * import modules that don't have named exports (e.g. [`apollo-server`](https://github.com/apollographql/apollo-server/issues/1356#issuecomment-565277759), [`node-influx`](https://github.com/node-influx/node-influx/issues/298)) 7 | * import your own modules without specifying an extension 8 | * lint with ESLint, with TypeScript support 9 | * test the TypeScript code instantly without having to build first 10 | * run the resulting JavaScript code, with support for the optional chaining operator `?.` 11 | 12 | Bonus: continuous integration script for GitHub Actions. It automatically runs tests on every pushed commit. 13 | 14 | There is no need for Babel. 15 | 16 | # Emit ES modules code 17 | 18 | In [`tsconfig.json`](tsconfig.json), set this in `compilerOptions`: 19 | 20 | ```json 21 | "target": "esnext", 22 | "module": "esnext", // Output `import`/`export` ES modules 23 | ``` 24 | 25 | 26 | # Import modules that use Node built-ins (`http`, `url` etc.) 27 | 28 | * run `npm install --save-dev @types/node` 29 | * in `tsconfig.json` under `compilerOptions`, set 30 | * `"moduleResolution": "node"`, so `tsc` can find modules [when targeting ES6+](https://github.com/Microsoft/TypeScript/issues/8189) 31 | * `"types": ["node"]` to avoid errors related to Node built-in modules 32 | 33 | 34 | # Import modules that don't have named exports 35 | 36 | Normally we could write in TypeScript 37 | 38 | import { InfluxDB } from 'influx'; 39 | 40 | but when generating ES modules code, that statement will be passed through as is, and will cause Node to fail with 41 | 42 | > SyntaxError: The requested module 'influx' does not provide an export named 'InfluxDB' 43 | 44 | because [`node-influx` doesn't provide named exports](https://github.com/node-influx/node-influx/issues/298) (and neither does an even more popular module, [`apollo-server`](https://github.com/apollographql/apollo-server/issues/1356#issuecomment-565277759)). 45 | 46 | One alternative would be to generate old ugly commonjs modules code by, 47 | 48 | * removing the `"type": "module"` line from `package.json`, and 49 | * changing the module line to `"module": "CommonJS"` in `tsconfig.json` (`allowSyntheticDefaultImports` also becomes unnecessary) 50 | 51 | What we'll do is import the entire module: 52 | 53 | ```js 54 | import Influx from 'influx'; 55 | const influx = new Influx.InfluxDB(); 56 | ``` 57 | 58 | However, this will generate `Error TS1192: Module '...' has no default export.` To prevent that, set `"allowSyntheticDefaultImports": true` in `tsconfig.json`. 59 | 60 | 61 | # Import your own modules without specifying an extension 62 | 63 | When transpiling, [TypeScript won't generate an extension for you](https://github.com/microsoft/TypeScript/issues/16577). Run Node with the [`node --experimental-specifier-resolution=node` parameter](https://nodejs.org/api/cli.html#cli_experimental_specifier_resolution_mode): 64 | 65 | node --experimental-specifier-resolution=node run.js 66 | 67 | Otherwise, [node mandates that you specify the extension](https://nodejs.org/api/esm.html#esm_mandatory_file_extensions) in the `import` statement. 68 | 69 | 70 | # Optional chaining 71 | 72 | To support optional chaining, add the `--harmony` flag to the node command line. 73 | 74 | 75 | # Run the resulting JavaScript code 76 | 77 | Add `"type": "module"` to `package.json`, because [TypeScript can't generate files with the .mjs extension](https://github.com/microsoft/TypeScript/issues/18442#issuecomment-581738714). 78 | 79 | 80 | # ESLint 81 | 82 | To be able to run `eslint`, we must create an `.eslintrc.cjs` file, rather than a `.js` one (due to `"type": "module"` in `package.json`). Then, install the required dependencies: 83 | 84 | npm i -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser 85 | 86 | Here's the [diff to add ESLint support](https://github.com/dandv/typescript-modern-project/commit/f816fe6e8d83ce554bd3066ac6638fb4406e917f). 87 | 88 | 89 | # Testing with Jest 90 | 91 | The cleanest way to fully support Jest with TypeScript, ES Modules and ESLint, is to use `ts-jest`, which has [a number of advantages over using Babel](https://github.com/kulshekhar/ts-jest#ts-jest). What we need to do: 92 | 93 | * `npm install --save-dev jest @types/jest eslint-plugin-jest` - for ES Lint support 94 | * add `"jest"` to the `types` array in `tsconfig.json` 95 | * add the `'jest'` plugin to `.eslintrc.cjs` and also add `'jest/globals': true` to its `env` key 96 | * use the [`jest.config.cjs`](jest.config.cjs) generated by ts-jest `config:init` (just renamed .js -> .cjs). 97 | 98 | Normally, to run Jest from `package.json`, we'd add a `"test": "jest"` line. That won't be sufficient, because we need to pass the `--harmony` flag to node (for optional chaining support). 99 | To pass parameters to Node when running Jest, we'll add the following `test` line: 100 | 101 | "test": "node --harmony node_modules/.bin/jest" 102 | 103 | The only caveat here is that Jest seems to prefer generated `.js` files over their `.ts` originals, so we'll exclude them via [`jest.config.cjs`](jest.config.cjs): 104 | 105 | ``` 106 | testRegex: '.*.test.ts', // test filenames matching this regex 107 | moduleFileExtensions: ['ts', 'js'], // modules are only in .ts files, but 'js' *must* be specified too 108 | ``` 109 | 110 | 111 | # Source maps 112 | 113 | If your script generates an error, you'll see the line numbers from the generated `.js` files, which is not helpful. We want to see the original paths and line numbers from the `.ts` files. To do that, we'll add `sourceMap: true` to `tsconfig.json`, install [`source-map-support`](https://www.npmjs.com/package/source-map-support) and run node with the `-r source-map-support/register` parameter. Note that Jest already takes care of source mapping so you'll see the `.ts` line numbers without having to do anything extra. 114 | 115 | Here's [the diff to add source map support](https://github.com/dandv/typescript-modern-project/commit/4e31278833f2ce07f474d9c6348bb4509082ee97). 116 | 117 | 118 | ## CI testing 119 | 120 | Using [GitHub Actions](https://github.com/features/actions), we can configure automatic testing via `.yml` files under [.github/workflows](.github/workflows). 121 | 122 | 123 | ## TODO 124 | 125 | The `tsconfig.json` settings generate `.js` built files, and `.js.map` source map files, next to the original `.ts` file. While some IDEs conveniently hide these files, it may be desirable to output them in a separate directory, typically `dist`. 126 | 127 | This can be done using the `rootDir`/`outDir` settings in `tsconfig.json`, but that sort of setup comes with an [annoying limitation](https://github.com/microsoft/TypeScript/issues/9858) of Typescript that [forbids importing files outside the `rootDir`](https://stackoverflow.com/questions/52121725/maintain-src-folder-structure-when-building-to-dist-folder-with-typescript-3). That can be a [problem with monorepos](https://github.com/microsoft/TypeScript/issues/17611). 128 | -------------------------------------------------------------------------------- /jest.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | testRegex: '.*.test.ts', // test filenames matching this regex 5 | moduleFileExtensions: ['ts', 'js'], // modules are only in .ts files, but 'js' *must* be specified too 6 | }; 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tsmodules", 3 | "version": "1.1.0", 4 | "description": "TypeScript project template to import modules without extension, and modules with default exports that use node built-ins", 5 | "keywords": [ 6 | "typescript", 7 | "modules", 8 | "es modules", 9 | "esnext", 10 | "influxdb", 11 | "apollo-server" 12 | ], 13 | "license": "MIT", 14 | "author": "dandv", 15 | "type": "module", 16 | "main": "run.js", 17 | "scripts": { 18 | "build": "npm run clean && tsc", 19 | "clean": "rm -f *.js *.js.map", 20 | "lint": "eslint *.ts", 21 | "start": "node --experimental-specifier-resolution=node --harmony -r source-map-support/register run.js", 22 | "test": "node --harmony node_modules/.bin/jest" 23 | }, 24 | "dependencies": { 25 | "influx": "^5.6.0" 26 | }, 27 | "devDependencies": { 28 | "@types/jest": "^26.0.7", 29 | "@types/node": "^14.0.26", 30 | "@typescript-eslint/eslint-plugin": "^3.7.0", 31 | "@typescript-eslint/parser": "^3.7.0", 32 | "eslint": "^7.5.0", 33 | "eslint-plugin-jest": "^23.18.2", 34 | "jest": "^26.1.0", 35 | "source-map-support": "^0.5.19", 36 | "ts-jest": "^26.1.3", 37 | "typescript": "^3.9.7" 38 | }, 39 | "engines": { 40 | "node": ">=13.0.0" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /run.ts: -------------------------------------------------------------------------------- 1 | // Import without specifying the extension. `./Lib.js` would look odd in a .ts file 2 | import { Lib } from './Lib'; 3 | 4 | // Can't use named imports because https://github.com/node-influx/node-influx/issues/298 5 | // import { InfluxDB } from 'influx'; 6 | // const influx = new InfluxDB(); 7 | 8 | import Influx from 'influx'; 9 | const influx = new Influx.InfluxDB(); 10 | if (influx instanceof Influx.InfluxDB) 11 | console.info('Module without named exports imported successfully'); 12 | 13 | const l = new Lib(); 14 | l.run(); 15 | 16 | try { 17 | throw new Error('testing source mapping'); 18 | } catch (e) { 19 | if (e.stack.includes('.ts:')) { 20 | console.info('Stack trace mapped back to TypeScript should indicate correct error line number'); 21 | console.info(e); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test.ts: -------------------------------------------------------------------------------- 1 | // Import without specifying the extension. `./Lib.js` would look odd in a .ts file 2 | import { Lib } from './Lib'; 3 | 4 | test('constructor', () => { 5 | const instance = new Lib(); 6 | expect(instance instanceof Lib).toBeTruthy(); 7 | }); 8 | 9 | try { 10 | throw new Error('testing source mapping in Jest'); 11 | } catch (e) { 12 | if (e.stack.includes('.ts:')) { 13 | console.info('Stack trace mapped back to TypeScript should indicate correct error line number'); 14 | console.info(e); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "module": "esnext", // output `import`/`export` ES modules 5 | //"module": "CommonJS", // enables `import { InfluxDB } from 'influx' 6 | "allowSyntheticDefaultImports": true, // allow default imports from modules with no default export. This does not affect code emit, just typechecking. 7 | "moduleResolution": "node", // find modules in node_modules - https://github.com/Microsoft/TypeScript/issues/8189#issuecomment-212079251 8 | "types": ["node", "jest"], // Influx uses built-in node modules like http or url 9 | "sourceMap": true 10 | } 11 | } 12 | --------------------------------------------------------------------------------