From 63212a4301e2090c852e07ca1ec32c08c0bd57f9 Mon Sep 17 00:00:00 2001 From: crusader Date: Sat, 25 Aug 2018 12:30:00 +0900 Subject: [PATCH] project initialized --- .editorconfig | 22 ++++ .gitignore | 23 ++++ .npmignore | 32 +++++ .npmrc | 2 + .prettierignore | 7 + .travis.yml | 9 ++ .vscode/extensions.json | 11 ++ .vscode/settings.json | 13 ++ .yarnrc | 1 + LICENSE.md | 21 +++ README.md | 236 ++++++++++++++++++++++++++++++++++ config/global.d.ts | 66 ++++++++++ config/helpers.js | 60 +++++++++ config/jest.config.js | 43 +++++++ config/prettier.config.js | 15 +++ config/rollup.config.js | 128 ++++++++++++++++++ config/setup-tests.js | 4 + config/tsconfig.json | 14 ++ config/types.js | 30 +++++ package.json | 119 +++++++++++++++++ scripts/copy.js | 47 +++++++ scripts/migrate.js | 221 +++++++++++++++++++++++++++++++ scripts/tsconfig.json | 8 ++ src/Greeter.ts | 17 +++ src/__tests__/Greeter.spec.ts | 32 +++++ src/environment.ts | 5 + src/index.ts | 1 + tsconfig.json | 33 +++++ tslint.json | 96 ++++++++++++++ 29 files changed, 1316 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 .npmignore create mode 100644 .npmrc create mode 100644 .prettierignore create mode 100644 .travis.yml create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.json create mode 100644 .yarnrc create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 config/global.d.ts create mode 100644 config/helpers.js create mode 100644 config/jest.config.js create mode 100644 config/prettier.config.js create mode 100644 config/rollup.config.js create mode 100644 config/setup-tests.js create mode 100644 config/tsconfig.json create mode 100644 config/types.js create mode 100644 package.json create mode 100644 scripts/copy.js create mode 100644 scripts/migrate.js create mode 100644 scripts/tsconfig.json create mode 100644 src/Greeter.ts create mode 100644 src/__tests__/Greeter.spec.ts create mode 100644 src/environment.ts create mode 100644 src/index.ts create mode 100644 tsconfig.json create mode 100644 tslint.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a0be7a4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# top-most EditorConfig file +root = true + +# all files +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +max_line_length = 80 + +[*.{js,ts}] +quote_type = single +curly_bracket_next_line = false +spaces_around_brackets = inside +indent_brace_style = BSD KNF + +# HTML +[*.html] +quote_type = double diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b20265 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +*.log +.idea +.DS_Store +.cache +node_modules + +coverage +lib +esm5 +lib-esm +esm2015 +lib-fesm +fesm +umd +bundles +typings +types +docs +dist + +## this is generated by `npm pack` +*.tgz +package diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..6dc8762 --- /dev/null +++ b/.npmignore @@ -0,0 +1,32 @@ +.* +*.log + +# tools configs +**/tsconfig.json +tsconfig.*.json +tslint.json +**/webpack.config.js +**/jest.config.js +**/prettier.config.js + +# build scripts +config/ +scripts/ + +# Test files +**/*.spec.js +**/*.test.js +**/*.test.d.ts +**/*.spec.d.ts +__tests__ +coverage + +# Sources +node_modules +src +docs +examples + +## this is generated by `npm pack` +*.tgz +package diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..64d71ed --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +access=public +save-exact=true diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..da9b102 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +bundles +esm5 +esm2015 +fesm +types +typings +dist diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..a3aabc6 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: '8' +cache: yarn +notifications: + email: false +install: + - yarn +script: + - yarn build diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..8b47b44 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,11 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp + "eg2.tslint", + "esbenp.prettier-vscode", + "codezombiech.gitignore", + "EditorConfig.EditorConfig" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..bed6d7e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,13 @@ +// Place your settings in this file to overwrite default and user settings. +{ + "tslint.autoFixOnSave": true, + "tslint.enable": true, + "editor.formatOnSave": true, + "typescript.format.enable": false, + "javascript.format.enable": false, + "typescript.referencesCodeLens.enabled": true, + "javascript.referencesCodeLens.enabled": true, + "editor.rulers": [ + 80,100 + ], +} diff --git a/.yarnrc b/.yarnrc new file mode 100644 index 0000000..95b8581 --- /dev/null +++ b/.yarnrc @@ -0,0 +1 @@ +save-prefix false diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5d44fc2 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Martin Hochel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3a7c5b4 --- /dev/null +++ b/README.md @@ -0,0 +1,236 @@ +# Typescript lib starter + +[![Greenkeeper badge](https://badges.greenkeeper.io/Hotell/typescript-lib-starter.svg)](https://greenkeeper.io/) + +[![Build Status](https://travis-ci.org/Hotell/typescript-lib-starter.svg?branch=master)](https://travis-ci.org/Hotell/typescript-lib-starter) +[![NPM version](https://img.shields.io/npm/v/%40martin_hotell%2Ftypescript-lib-starter.svg)](https://www.npmjs.com/package/@martin_hotell/typescript-lib-starter) +![Downloads](https://img.shields.io/npm/dm/@martin_hotell/typescript-lib-starter.svg) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) + +This npm library starter: + +- creates package for both Node and Browser +- build will creates 4 standard "package" formats: + - `umd` 👉 UMD bundle for Node and Browser + > `main` field in package.json + - `esm5` 👉 transpiled files to ES5 + es2015 modules for tree shaking + > `module` field in package.json + - `esm2015` 👉 raw javascript files transpiled from typescript to latest ES standard ( es2018 ) + > `es2015` field in package.json + > + > this is useful if you wanna transpile everything or just wanna ship untranspiled esNext code for evergreen browsers) + - `fesm` 👉 experimental bundle type introduced by Angular team (TL;DR: it's an es2015 flattened bundle, like UMD but with latest ECMAscript and JS modules) +- type definitions are automatically generated and shipped with your package + - > `types` field in package.json +- `sideEffects` 👉 [support proper tree-shaking](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free) for whole library ( Webpack >= 4). Turn this off or adjust as needed if your modules are not pure! + +## Start coding in 4 steps ! + +1. `git clone https://github.com/Hotell/typescript-lib-starter && cd $_` + +2. `rm -rf .git && git init` + +3. in `package.json` reset following fields: + +```diff +{ +- "name": "@next-gen/typescript-lib-starter", ++ "name": "{yourLibraryPackageName}", +- "version": "1.7.0", ++ "version": "1.0.0", +- "description": "TypeScript library setup for multiple compilation targets using tsc and webpack", ++ "description": "What is your library all about...", +- "author": "Martin Hochel", ++ "author": "{yourName}", +- "license": "MIT", ++ "license": "{yourLicense}", + "repository": { + "type": "git", +- "url": "https://www.github.com/Hotell/typescript-lib-starter" ++ "url": "https://www.github.com/{yourAccountName}/{yourLibraryPackageName}" + } +} +``` + +4. Install all dependencies `yarn install` + +Happy coding ! 🖖 + +## Consumption of published library: + +1. install it 🤖 + +```sh +yarn add my-new-library +# OR +npm install my-new-library +``` + +1. use it 💪 + +### Webpack + +> #### NOTE: +> +> Don't forget to turn off ES modules transpilation to enable tree-shaking! +> +> - babel: `{"modules": false}` +> - typescript: `{"module": "esnext"}` + +```ts +// main.ts or main.js +import { Greeter } from 'my-new-library' + +const mountPoint = document.getElementById('app') +const App = () => { + const greeter = new Greeter('Stranger') + return `

${greeter.greet()}

` +} +const render = (Root: Function, where: HTMLElement) => { + where.innerHTML = Root() +} + +render(App, mountPoint) +``` + +```html + + + + + + +
+ + +``` + +### UMD/ES2015 module aware browsers ( no bundler ) + +```html + + + + + + + +
+ + +``` + +## Publish your library + +> #### NOTE: +> +> you have to create npm account and register token on your machine +> 👉 `npm adduser` +> +> If you are using scope ( you definitely should 👌) don't forget to [`--scope`](https://docs.npmjs.com/cli/adduser#scope) + +Execute `yarn release` which will handle following tasks: + +- bump package version and git tag +- update/(create if it doesn't exist) CHANGELOG.md +- push to github master branch + push tags +- publish build packages to npm + +> **NOTE:** +> +> all package files are gonna be within `/dist` folder from where `npm publish` will be executed + +> releases are handled by awesome [standard-version](https://github.com/conventional-changelog/standard-version) + +### Initial Release (without bumping package.json version): + +`yarn release --first-release` + +### Pre-release + +- To get from `1.1.2` to `1.1.2-0`: + +`yarn release --prerelease` + +- **Alpha**: To get from `1.1.2` to `1.1.2-alpha.0`: + +`yarn release --prerelease alpha` + +- **Beta**: To get from `1.1.2` to `1.1.2-beta.0`: + +`yarn release --prerelease beta` + +### Dry run mode + +See what commands would be run, without committing to git or updating files + +`yarn release --dry-run` + +## Check what files are gonna be published to npm + +- `cd dist && yarn pack` OR `yarn release:preflight` which will create a tarball with everything that would get published to NPM + +## Check size of your published NPM bundle + +`yarn size` + +## Format and fix lint errors + +`yarn ts:style:fix` + +## Generate documentation + +`yarn docs` + +## Commit ( via commitizen ) + +- this is preferred way how to create conventional-changelog valid commits +- if you prefer your custom tool we provide a commit hook linter which will error out, it you provide invalid commit message +- if you are in rush and just wanna skip commit message validation just prefix your message with `WIP: something done` ( if you do this please squash your work when you're done with proper commit message so standard-version can create Changelog and bump version of your library appropriately ) + +`yarn commit` - will invoke [commitizen CLI](https://github.com/commitizen/cz-cli) + +### Troubleshooting + +#### dynamic `import()` + +This starter uses latest **TypeScript >=2.9** which has support for lazy loading chunks/modules via `import()` and also definition acquisition via [`import('../path-to-module').TypeFoo`](http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#import-types) + +Before TS 2.9, it wasn't possible to properly generate ambient definitions if you used dynamic `import()`. This works now as expected without any hacks ❤️ ! + +--- + +> ### Before TS 2.9 +> +> Please note that if you wanna use that feature, compiler will complain because declaration generation is turned on, and currently TS can't handle type generation with types that will be loaded in the future ( lazily ) +> +> **How to solve this:** +> +> - turn of type checking and don't generate types for that lazy import: `import('./components/button') as any` +> - or you can use this [temporary workaround](https://github.com/Microsoft/TypeScript/issues/16603#issuecomment-310208259) diff --git a/config/global.d.ts b/config/global.d.ts new file mode 100644 index 0000000..5b6af9e --- /dev/null +++ b/config/global.d.ts @@ -0,0 +1,66 @@ +// ts-jest types require 'babel-core' +declare module 'babel-core' { + interface TransformOptions {} +} + +declare module 'jest-config' { + const defaults: jest.DefaultOptions +} + +declare module 'sort-object-keys' { + const sortPackageJson: ( + object: T, + sortWith?: (...args: any[]) => any + ) => T + export = sortPackageJson +} + +type RollupPluginFn = ( + options?: O +) => import('rollup').Plugin + +declare module 'rollup-plugin-json' { + export interface Options { + /** + * All JSON files will be parsed by default, but you can also specifically include/exclude files + */ + include?: string | string[] + exclude?: string | string[] + /** + * for tree-shaking, properties will be declared as variables, using either `var` or `const` + * @default false + */ + preferConst?: boolean + /** + * specify indentation for the generated default export — defaults to '\t' + * @default '\t' + */ + indent?: string + } + const plugin: RollupPluginFn + export default plugin +} +declare module 'rollup-plugin-sourcemaps' { + const plugin: RollupPluginFn + export default plugin +} +declare module 'rollup-plugin-node-resolve' { + const plugin: RollupPluginFn + export default plugin +} +declare module 'rollup-plugin-commonjs' { + const plugin: RollupPluginFn + export default plugin +} +declare module 'rollup-plugin-replace' { + const plugin: RollupPluginFn + export default plugin +} +declare module 'rollup-plugin-uglify' { + const uglify: RollupPluginFn + export { uglify } +} +declare module 'rollup-plugin-terser' { + const terser: RollupPluginFn + export { terser } +} diff --git a/config/helpers.js b/config/helpers.js new file mode 100644 index 0000000..e87f3e2 --- /dev/null +++ b/config/helpers.js @@ -0,0 +1,60 @@ +// helpers +module.exports = { + camelCaseToDash, + dashToCamelCase, + toUpperCase, + pascalCase, + normalizePackageName, + getOutputFileName, +} + +/** + * + * @param {string} myStr + */ +function camelCaseToDash(myStr) { + return myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() +} + +/** + * + * @param {string} myStr + */ +function dashToCamelCase(myStr) { + return myStr.replace(/-([a-z])/g, (g) => g[1].toUpperCase()) +} + +/** + * + * @param {string} myStr + */ +function toUpperCase(myStr) { + return `${myStr.charAt(0).toUpperCase()}${myStr.substr(1)}` +} + +/** + * + * @param {string} myStr + */ +function pascalCase(myStr) { + return toUpperCase(dashToCamelCase(myStr)) +} + +/** + * + * @param {string} rawPackageName + */ +function normalizePackageName(rawPackageName) { + const scopeEnd = rawPackageName.indexOf('/') + 1 + + return rawPackageName.substring(scopeEnd) +} + +/** + * + * @param {string} fileName + * @param {boolean?} isProd + */ +function getOutputFileName(fileName, isProd = false) { + return isProd ? fileName.replace(/\.js$/, '.min.js') : fileName +} diff --git a/config/jest.config.js b/config/jest.config.js new file mode 100644 index 0000000..d67d427 --- /dev/null +++ b/config/jest.config.js @@ -0,0 +1,43 @@ +// @ts-check + +const { defaults } = require('jest-config') + +/** + * @type {import('./types').TsJestConfig} + */ +const tsJestConfig = { + skipBabel: true, +} + +/** + * @type {Partial} + */ +const config = { + rootDir: '..', + transform: { + '^.+\\.(ts|tsx)$': 'ts-jest', + }, + testMatch: [ + '/src/**/__tests__/**/*.ts?(x)', + '/src/**/?(*.)+(spec|test).ts?(x)', + ], + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + globals: { + 'ts-jest': tsJestConfig, + }, + coverageThreshold: { + global: { + branches: 80, + functions: 80, + lines: 80, + statements: 80, + }, + }, + setupFiles: ['/config/setup-tests.js'], + watchPlugins: [ + 'jest-watch-typeahead/filename', + 'jest-watch-typeahead/testname', + ], +} + +module.exports = config diff --git a/config/prettier.config.js b/config/prettier.config.js new file mode 100644 index 0000000..2827eb2 --- /dev/null +++ b/config/prettier.config.js @@ -0,0 +1,15 @@ +// @ts-check + +/** + * @type {import('./types').PrettierConfig} + */ +const config = { + singleQuote: true, + arrowParens: 'always', + semi: false, + bracketSpacing: true, + trailingComma: 'es5', + printWidth: 80, +} + +module.exports = config diff --git a/config/rollup.config.js b/config/rollup.config.js new file mode 100644 index 0000000..65e003e --- /dev/null +++ b/config/rollup.config.js @@ -0,0 +1,128 @@ +import { resolve } from 'path' +import sourceMaps from 'rollup-plugin-sourcemaps' +import nodeResolve from 'rollup-plugin-node-resolve' +import json from 'rollup-plugin-json' +import commonjs from 'rollup-plugin-commonjs' +import replace from 'rollup-plugin-replace' +import { uglify } from 'rollup-plugin-uglify' +import { terser } from 'rollup-plugin-terser' +import { getIfUtils, removeEmpty } from 'webpack-config-utils' + +import pkg from '../package.json' +const { + pascalCase, + normalizePackageName, + getOutputFileName, +} = require('./helpers') + +/** + * @typedef {import('./types').RollupConfig} Config + */ +/** + * @typedef {import('./types').RollupPlugin} Plugin + */ + +const env = process.env.NODE_ENV || 'development' +const { ifProduction } = getIfUtils(env) + +const LIB_NAME = pascalCase(normalizePackageName(pkg.name)) +const ROOT = resolve(__dirname, '..') +const DIST = resolve(ROOT, 'dist') + +/** + * @type {{entry:{esm5: string, esm2015: string},bundles:string}} + */ +const PATHS = { + entry: { + esm5: resolve(DIST, 'esm5'), + esm2015: resolve(DIST, 'esm2015'), + }, + bundles: resolve(DIST, 'bundles'), +} + +/** + * @type {string[]} + */ +const external = Object.keys(pkg.peerDependencies) || [] + +/** + * @type {Plugin[]} + */ +const plugins = /** @type {Plugin[]} */ ([ + // Allow json resolution + json(), + + // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) + commonjs(), + + // Allow node_modules resolution, so you can use 'external' to control + // which external modules to include in the bundle + // https://github.com/rollup/rollup-plugin-node-resolve#usage + nodeResolve(), + + // Resolve source maps to the original source + sourceMaps(), + + // properly set process.env.NODE_ENV within `./environment.ts` + replace({ + exclude: 'node_modules/**', + 'process.env.NODE_ENV': JSON.stringify(env), + }), +]) + +/** + * @type {Config} + */ +const CommonConfig = { + input: {}, + output: {}, + inlineDynamicImports: true, + // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') + external, +} + +/** + * @type {Config} + */ +const UMDconfig = { + ...CommonConfig, + input: resolve(PATHS.entry.esm5, 'index.js'), + output: { + file: getOutputFileName( + resolve(PATHS.bundles, 'index.umd.js'), + ifProduction() + ), + // file: getOutputFileName('dist/bundles/index.umd.js', ifProduction()), + format: 'umd', + name: LIB_NAME, + sourcemap: true, + }, + plugins: /** @type {Plugin[]} */ (removeEmpty([ + ...plugins, + ifProduction(uglify()), + ])), +} + +/** + * @type {Config} + */ +const FESMconfig = { + ...CommonConfig, + input: resolve(PATHS.entry.esm2015, 'index.js'), + output: [ + { + file: getOutputFileName( + resolve(PATHS.bundles, 'index.esm.js'), + ifProduction() + ), + format: 'es', + sourcemap: true, + }, + ], + plugins: /** @type {Plugin[]} */ (removeEmpty([ + ...plugins, + ifProduction(terser()), + ])), +} + +export default [UMDconfig, FESMconfig] diff --git a/config/setup-tests.js b/config/setup-tests.js new file mode 100644 index 0000000..c0c91c6 --- /dev/null +++ b/config/setup-tests.js @@ -0,0 +1,4 @@ +// add here any code that you wanna execute before tests like +// - polyfills +// - some custom code +// for more docs check see https://jestjs.io/docs/en/configuration.html#setupfiles-array diff --git a/config/tsconfig.json b/config/tsconfig.json new file mode 100644 index 0000000..0117857 --- /dev/null +++ b/config/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "strict": true, + "allowJs": true, + "checkJs": true, + "target": "es2017", + "module": "commonjs", + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "noEmit": true + } +} \ No newline at end of file diff --git a/config/types.js b/config/types.js new file mode 100644 index 0000000..bbe72d1 --- /dev/null +++ b/config/types.js @@ -0,0 +1,30 @@ +export {} + +// ===== JEST ==== + +/** + * @typedef {import('ts-jest/dist/jest-types').TsJestConfig} TsJestConfig + */ + +// @TODO https://github.com/Microsoft/TypeScript/issues/24916 +/** + * @typedef {Partial} JestConfig + */ + +/** + * @typedef {typeof import('jest-config').defaults} JestDefaultConfig + */ + +// ==== PRETTIER ==== +/** + * @typedef {import('prettier').Options} PrettierConfig + */ + +// ==== ROLLUP ==== +/** + * @typedef {import('rollup').InputOptions & { output: import('rollup').OutputOptions | Array }} RollupConfig + */ + +/** + * @typedef {import('rollup').Plugin} RollupPlugin + */ diff --git a/package.json b/package.json new file mode 100644 index 0000000..756bd26 --- /dev/null +++ b/package.json @@ -0,0 +1,119 @@ +{ + "name": "@overflow/typescript-library-starter", + "version": "0.0.1", + "description": "TypeScript library setup for multiple compilation targets using tsc and webpack", + "main": "./bundles/index.umd.js", + "module": "./esm5/index.js", + "es2015": "./esm2015/index.js", + "typings": "./types/index.d.ts", + "sideEffects": false, + "repository": { + "type": "git", + "url": "https://www.github.com/Hotell/typescript-lib-starter" + }, + "author": "loafle.com", + "license": "MIT", + "engines": { + "node": ">=8.5" + }, + "scripts": { + "cleanup": "shx rm -rf dist", + "prebuild": "yarn cleanup && yarn verify", + "build": "tsc && tsc --target es2018 --outDir dist/esm2015 && rollup -c config/rollup.config.js && rollup -c config/rollup.config.js --environment NODE_ENV:production", + "postbuild": "node scripts/copy.js && yarn size", + "docs": "typedoc -p . --theme minimal --target 'es6' --excludeNotExported --excludePrivate --ignoreCompilerErrors --exclude \"**/src/**/__tests__/*.*\" --out docs src/", + "test": "jest -c ./config/jest.config.js", + "test:watch": "yarn test -- --watch", + "test:coverage": "yarn test -- --coverage", + "test:ci": "yarn test -- --ci", + "validate-js": "tsc -p ./config && tsc -p ./scripts", + "verify": "yarn validate-js && yarn style && yarn test:ci", + "commit": "git-cz", + "style": "yarn format -- --list-different && yarn lint", + "style:fix": "yarn format:fix && yarn lint:fix", + "format": "prettier --config config/prettier.config.js \"**/*.{ts,tsx,js,jsx,css,scss,sass,less,md}\"", + "format:fix": "yarn format -- --write", + "lint": "tslint --project tsconfig.json --format codeFrame", + "lint:fix": "yarn lint -- --fix", + "prerelease": "yarn build", + "release": "standard-version", + "postrelease": "node scripts/copy.js && yarn release:github && yarn release:npm", + "release:github": "git push --no-verify --follow-tags origin master", + "release:npm": "cd dist && yarn publish", + "release:preflight": "cd dist && yarn pack", + "size": "yarn size:umd && yarn size:fesm", + "size:umd": "shx echo \"Gzipped+minified UMD bundle Size:\" && cross-var strip-json-comments --no-whitespace \"./dist/bundles/index.umd.min.js\" | gzip-size", + "size:fesm": "shx echo \"Gzipped+minified FESM bundle Size:\" && strip-json-comments --no-whitespace \"./dist/bundles/index.esm.min.js\" | gzip-size" + }, + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + }, + "validate-commit-msg": { + "types": "conventional-commit-types", + "maxSubjectLength": 120 + } + }, + "husky": { + "hooks": { + "commit-msg": "validate-commit-msg", + "pre-commit": "lint-staged", + "pre-push": "yarn style && yarn test -- --bail --onlyChanged" + } + }, + "lint-staged": { + "**/*.{ts,tsx,js,jsx,css,scss,sass,less,md}": [ + "prettier --config config/prettier.config.js --write", + "git add" + ], + "src/**/*.{ts,tsx}": [ + "yarn lint:fix", + "git add" + ] + }, + "peerDependencies": { + "tslib": ">=1.9.0" + }, + "dependencies": {}, + "devDependencies": { + "@types/chokidar": "1.7.5", + "@types/jest": "23.3.1", + "@types/json5": "0.0.29", + "@types/node": "10.7.0", + "@types/prettier": "1.13.2", + "@types/webpack-config-utils": "2.3.0", + "awesome-typescript-loader": "5.2.0", + "commitizen": "2.10.1", + "cross-var": "1.1.0", + "cz-conventional-changelog": "2.1.0", + "gzip-size-cli": "3.0.0", + "husky": "1.0.0-rc.13", + "jest": "23.5.0", + "jest-watch-typeahead": "0.2.0", + "json5": "1.0.1", + "lint-staged": "7.2.2", + "prettier": "1.14.2", + "rollup": "0.64.1", + "rollup-plugin-commonjs": "9.1.5", + "rollup-plugin-json": "3.0.0", + "rollup-plugin-node-resolve": "3.3.0", + "rollup-plugin-replace": "2.0.0", + "rollup-plugin-sourcemaps": "0.4.2", + "rollup-plugin-terser": "1.0.1", + "rollup-plugin-uglify": "4.0.0", + "shx": "0.3.2", + "sort-object-keys": "1.1.2", + "standard-version": "4.4.0", + "strip-json-comments-cli": "1.0.1", + "ts-jest": "23.1.3", + "tslib": "1.9.3", + "tslint": "5.11.0", + "tslint-config-prettier": "1.14.0", + "tslint-config-standard": "7.1.0", + "tslint-react": "3.6.0", + "typedoc": "0.11.1", + "typescript": "2.9.2", + "validate-commit-msg": "2.14.0", + "webpack-config-utils": "2.3.0" + } +} \ No newline at end of file diff --git a/scripts/copy.js b/scripts/copy.js new file mode 100644 index 0000000..e8ea9ce --- /dev/null +++ b/scripts/copy.js @@ -0,0 +1,47 @@ +const { writeFileSync, copyFileSync } = require('fs') +const { resolve } = require('path') +const packageJson = require('../package.json') + +main() + +function main() { + const projectRoot = resolve(__dirname, '..') + const distPath = resolve(projectRoot, 'dist') + const distPackageJson = createDistPackageJson(packageJson) + + copyFileSync( + resolve(projectRoot, 'README.md'), + resolve(distPath, 'README.md') + ) + copyFileSync( + resolve(projectRoot, 'CHANGELOG.md'), + resolve(distPath, 'CHANGELOG.md') + ) + copyFileSync( + resolve(projectRoot, 'LICENSE.md'), + resolve(distPath, 'LICENSE.md') + ) + copyFileSync( + resolve(projectRoot, '.npmignore'), + resolve(distPath, '.npmignore') + ) + writeFileSync(resolve(distPath, 'package.json'), distPackageJson) +} + +/** + * @param {typeof packageJson} packageConfig + * @return {string} + */ +function createDistPackageJson(packageConfig) { + const { + devDependencies, + scripts, + engines, + config, + husky, + 'lint-staged': lintStaged, + ...distPackageJson + } = packageConfig + + return JSON.stringify(distPackageJson, null, 2) +} diff --git a/scripts/migrate.js b/scripts/migrate.js new file mode 100644 index 0000000..096a600 --- /dev/null +++ b/scripts/migrate.js @@ -0,0 +1,221 @@ +/** + * Migrate Typescript-library-starter from 3. -> 4. + */ + +const JSON5 = require('json5') +const sortObjectByKeyNameList = require('sort-object-keys') +const { + writeFileSync, + copyFileSync, + readFileSync, + existsSync, + unlinkSync, +} = require('fs') +const { resolve, join } = require('path') +const starterPkg = require('../package.json') +const args = process.argv.slice(2) +const pathToProject = args[0] + +/** + * @typedef {typeof projectPkg} Pkg + */ + +if (!pathToProject) { + throw new Error( + 'you need provide relative path to package that uses ts-lib-starter!' + ) +} + +const ROOT = resolve(__dirname, '..') +const PACKAGE_ROOT = resolve(ROOT, pathToProject) + +main() + +function main() { + if (!existsSync(PACKAGE_ROOT)) { + throw new Error(`${PACKAGE_ROOT}, doesn't exists`) + } + + console.log('Migration initialized 👀') + + console.log('path to Package:', PACKAGE_ROOT) + + updatePackageJson() + updateTsConfig() + updateTsLintConfig() + updateConfigDir() + updateScriptsDir() + + console.log('DONE ✅') +} + +function updatePackageJson() { + const libPackagePkgPath = resolve(PACKAGE_ROOT, 'package.json') + + /** + * @type {typeof starterPkg} + */ + const libPackagePkg = JSON5.parse( + readFileSync(libPackagePkgPath, { encoding: 'utf-8' }) + ) + + /** + * @type {typeof starterPkg} + */ + const updatePkg = { + ...libPackagePkg, + main: starterPkg.main, + engines: { ...libPackagePkg.engines, ...starterPkg.engines }, + scripts: { ...libPackagePkg.scripts, ...starterPkg.scripts }, + peerDependencies: sortObjectByKeyNameList({ + ...libPackagePkg.peerDependencies, + ...starterPkg.peerDependencies, + }), + devDependencies: sortObjectByKeyNameList({ + ...starterPkg.devDependencies, + ...libPackagePkg.devDependencies, + }), + } + + removePackages(updatePkg.devDependencies) + writePackage(updatePkg) + + /** + * + * @param {{[packageName:string]:string}} devDependencies + */ + function removePackages(devDependencies) { + const depsToRemove = [ + '@types/uglifyjs-webpack-plugin', + '@types/webpack', + 'uglifyjs-webpack-plugin', + 'webpack', + 'webpack-cli', + // packages needed for this script + 'json5', + '@types/json5', + 'sort-object-keys', + ] + + depsToRemove.forEach( + (dependencyName) => delete devDependencies[dependencyName] + ) + } + + /** + * @param {typeof starterPkg} pkg + */ + function writePackage(pkg) { + const updatedLibPkgToWrite = JSON.stringify(pkg, null, 2) + writeFileSync(join(PACKAGE_ROOT, 'package.json'), updatedLibPkgToWrite) + + console.log('\n updated package.json:', updatedLibPkgToWrite, '\n') + } +} + +function updateTsConfig() { + /** + * @typedef {typeof import('../tsconfig.json')} TsConfig + */ + + const starterConfigPath = resolve(ROOT, 'tsconfig.json') + const libPackageConfigPath = resolve(PACKAGE_ROOT, 'tsconfig.json') + + /** + * @type {TsConfig} + */ + const starterConfig = JSON5.parse( + readFileSync(starterConfigPath, { encoding: 'utf-8' }) + ) + + /** + * @type {TsConfig} + */ + const libConfig = JSON5.parse( + readFileSync(libPackageConfigPath, { encoding: 'utf-8' }) + ) + + console.log('starter:', starterConfig) + console.log('library:', libConfig) + + console.log('==TS-Config:nothing updated==\n') +} + +function updateTsLintConfig() { + /** + * @typedef {typeof import('../tslint.json')} TsLintConfig + */ + + const starterConfigPath = resolve(ROOT, 'tslint.json') + const libPackageConfigPath = resolve(PACKAGE_ROOT, 'tslint.json') + + /** + * @type {TsLintConfig} + */ + const starterConfig = JSON5.parse( + readFileSync(starterConfigPath, { encoding: 'utf-8' }) + ) + + /** + * @type {TsLintConfig} + */ + const libConfig = JSON5.parse( + readFileSync(libPackageConfigPath, { encoding: 'utf-8' }) + ) + + console.log('starter:', starterConfig) + console.log('library:', libConfig) + + console.log('==TS-Lint:nothing updated==\n') +} + +function updateConfigDir() { + const starterConfigPathDir = resolve(ROOT, 'config') + const libPackageConfigPathDir = resolve(PACKAGE_ROOT, 'config') + + const filesToCopy = [ + 'global.d.ts', + 'helpers.js', + 'rollup.config.js', + 'tsconfig.json', + 'types.js', + ] + const filesToRemove = ['webpack.config.js'] + + filesToCopy.forEach((file) => { + copyFileSync( + resolve(starterConfigPathDir, file), + join(libPackageConfigPathDir, file) + ) + }) + + filesToRemove.forEach((file) => { + unlinkSync(join(libPackageConfigPathDir, file)) + }) + + console.log('==config/ updated==\n') +} + +function updateScriptsDir() { + const starterScriptsPathDir = resolve(ROOT, 'scripts') + const libPackageScriptsPathDir = resolve(PACKAGE_ROOT, 'scripts') + + const filesToCopy = ['copy.js', 'tsconfig.json'] + /** + * @type {string[]} + */ + const filesToRemove = [] + + filesToCopy.forEach((file) => { + copyFileSync( + resolve(starterScriptsPathDir, file), + join(libPackageScriptsPathDir, file) + ) + }) + + filesToRemove.forEach((file) => { + unlinkSync(join(libPackageScriptsPathDir, file)) + }) + + console.log('==scripts/ updated==\n') +} diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 0000000..e724c8d --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../config/tsconfig.json", + "compilerOptions": {}, + "include": [ + ".", + "../config/global.d.ts" + ] +} diff --git a/src/Greeter.ts b/src/Greeter.ts new file mode 100644 index 0000000..c3dc7ff --- /dev/null +++ b/src/Greeter.ts @@ -0,0 +1,17 @@ +import { IS_DEV } from './environment' + +export class Greeter { + constructor(private greeting: string) {} + greet() { + return `Hello, ${this.greeting}!` + } + + greetMe() { + /* istanbul ignore next line */ + if (IS_DEV) { + console.warn('this method is deprecated, use #greet instead') + } + + return this.greet() + } +} diff --git a/src/__tests__/Greeter.spec.ts b/src/__tests__/Greeter.spec.ts new file mode 100644 index 0000000..02900b7 --- /dev/null +++ b/src/__tests__/Greeter.spec.ts @@ -0,0 +1,32 @@ +jest.mock('../environment.ts', () => ({ + IS_DEV: true, + IS_PROD: false, +})) + +import { Greeter } from '../Greeter' + +describe(`Greeter`, () => { + let greeter: Greeter + + beforeEach(() => { + greeter = new Greeter('World') + }) + + it(`should greet`, () => { + const actual = greeter.greet() + const expected = 'Hello, World!' + + expect(actual).toBe(expected) + }) + + it(`should greet and print deprecation message if in dev mode`, () => { + const spyWarn = jest.spyOn(console, 'warn') + const actual = greeter.greetMe() + const expected = 'Hello, World!' + + expect(actual).toBe(expected) + expect(spyWarn).toHaveBeenCalledWith( + 'this method is deprecated, use #greet instead' + ) + }) +}) diff --git a/src/environment.ts b/src/environment.ts new file mode 100644 index 0000000..97464fa --- /dev/null +++ b/src/environment.ts @@ -0,0 +1,5 @@ +/** * @internal */ +export const IS_DEV = process.env.NODE_ENV === 'development' + +/** * @internal */ +export const IS_PROD = process.env.NODE_ENV === 'production' diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..54ffa06 --- /dev/null +++ b/src/index.ts @@ -0,0 +1 @@ +export { Greeter } from './Greeter' diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..5f93e29 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "moduleResolution": "node", + "module": "esnext", + "target": "es5", + "lib": [ + "dom", + "es2018" + ], + "strict": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "suppressImplicitAnyIndexErrors": true, + "forceConsistentCasingInFileNames": true, + "sourceMap": true, + "outDir": "dist/esm5", + "declaration": true, + "declarationDir": "dist/types", + "declarationMap": true, + "stripInternal": true, + "resolveJsonModule": true, + "importHelpers": true + }, + "include": [ + "./src" + ], + "exclude": [ + "node_modules", + "dist" + ], + "compileOnSave": false, + "buildOnSave": false +} \ No newline at end of file diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000..d677227 --- /dev/null +++ b/tslint.json @@ -0,0 +1,96 @@ +{ + "extends": [ + "tslint-config-standard", + "tslint-react", + "tslint-config-prettier" + ], + "rules": { + // tslint-react rules + "jsx-no-lambda": true, + "jsx-no-string-ref": true, + "jsx-self-close": true, + "jsx-boolean-value": [ + true, + "never" + ], + // core ts-lint rules + "await-promise": true, + "no-unused-variable": true, + "forin": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-shadowed-variable": true, + "no-string-literal": true, + "no-inferrable-types": [ + true + ], + "no-unnecessary-initializer": true, + "no-magic-numbers": true, + "no-require-imports": true, + "no-duplicate-super": true, + "no-boolean-literal-compare": true, + "no-namespace": [ + true, + "allow-declarations" + ], + "no-invalid-this": [ + true, + "check-function-in-method" + ], + "ordered-imports": [ + true + ], + "interface-name": [ + false + ], + "newline-before-return": true, + "object-literal-shorthand": true, + "arrow-return-shorthand": [ + true + ], + "unified-signatures": true, + "prefer-for-of": true, + "match-default-export-name": true, + "prefer-const": true, + "ban-types": [ + true, + [ + "Object", + "Avoid using the `Object` type. Did you mean `object`?" + ], + [ + "Function", + "Avoid using the `Function` type. Prefer a specific function type, like `() => void`." + ], + [ + "Boolean", + "Avoid using the `Boolean` type. Did you mean `boolean`?" + ], + [ + "Number", + "Avoid using the `Number` type. Did you mean `number`?" + ], + [ + "String", + "Avoid using the `String` type. Did you mean `string`?" + ], + [ + "Symbol", + "Avoid using the `Symbol` type. Did you mean `symbol`?" + ], + [ + "Array", + "Avoid using the `Array` type. Use 'type[]' instead." + ] + ] + } +}