├── .github └── ISSUE_TEMPLATE │ └── bug_report.md ├── .gitignore ├── .storybook ├── main.ts └── preview.ts ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── package.json ├── src ├── PhoneFormatter.tsx ├── as-you-type.cjs ├── index.ts ├── lazy.tsx └── stories │ └── story.stories.jsx ├── tsconfig.json └── vite.config.js /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /.storybook/main.ts: -------------------------------------------------------------------------------- 1 | import type { StorybookConfig } from "@storybook/react-vite"; 2 | 3 | const config: StorybookConfig = { 4 | stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"], 5 | addons: [ 6 | "@storybook/addon-links", 7 | "@storybook/addon-essentials", 8 | "@storybook/addon-onboarding", 9 | "@storybook/addon-interactions", 10 | ], 11 | framework: { 12 | name: "@storybook/react-vite", 13 | options: {}, 14 | }, 15 | docs: { 16 | autodocs: "tag", 17 | }, 18 | }; 19 | export default config; 20 | -------------------------------------------------------------------------------- /.storybook/preview.ts: -------------------------------------------------------------------------------- 1 | import type { Preview } from "@storybook/react"; 2 | 3 | const preview: Preview = { 4 | parameters: { 5 | actions: { argTypesRegex: "^on[A-Z].*" }, 6 | controls: { 7 | matchers: { 8 | color: /(background|color)$/i, 9 | date: /Date$/, 10 | }, 11 | }, 12 | }, 13 | }; 14 | 15 | export default preview; 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at hello@mintere.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Ben Aubin 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Headless Phone Input 2 | 3 | A headless phone number input component built for usability. 4 | 5 | [Phone numbers are hard][falsehoods]. Users expect to be able to enter phone numbers in the format they're used to. Here's the problem: most people are used to national - or even local phone number formats. If you offload phone number validation to your backend (or an API), resolving the ambiguity becomes difficult or even impossible. 6 | 7 | This component helps you build a UI that gracefully guides your users towards unambiguous phone number formats. And you get the result in standard e164 format: ready for use with any telephony service. 8 | 9 | Other libraries are generally heavy (phone number rulesets can be big - 99.1% of this library's [footprint][bundlephobia] is due to [libphonenumber-js]), force you to use their UI, and can't handle copy & paste or edit-in-place. `react-headless-phone-input` is designed for usability-first, and lets you bring your own input components. In fact, your existing input fields will almost certainly work with no modifications. Plus, it supports optional lazy-loading with progressive enhancement powered by React Suspense. 10 | 11 | Built with React Hooks. 12 | 13 | [Demo][demo] 14 | 15 | ## Install 16 | 17 | Install both react-headless-input and [libphonenumber-js]: 18 | 19 | ```sh 20 | npm i --save react-headless-phone-input libphonenumber-js 21 | ``` 22 | 23 | or 24 | 25 | ```sh 26 | yarn add react-headless-phone-input libphonenumber-js 27 | ``` 28 | 29 | ## Features 30 | 31 | - 100% headless: Bring your own UI. You can use almost any input component you already have 32 | - Lets users copy & paste phone numbers of any format 33 | - Typescript support 34 | - Built-in lazy-loading with progressive enhancement (clocks in at 40KB without lazy-loading) 35 | - Detects the associated country, enabling international phone input. 36 | - Lets users copy & paste phone numbers of any format 37 | - Acts like a normal input: Doesn’t glitch if a user edits in-place or deletes template characters 38 | - Validates number plausibility 39 | - External state is standard e164 format 40 | 41 | ## Example 42 | 43 | This library is headless: you bring your own UI, but it's almost as easy as using regular inputs. 44 | 45 | Here's an example using [tiny-flag-react] to show the flag associated with the number's country: 46 | 47 | ```js 48 | import TinyFlagReact from "tiny-flag-react"; 49 | import PhoneFormatter from "react-headless-phone-input"; 50 | // import PhoneFormatter from "react-headless-phone-input/lazy"; RECOMMENDED 51 | 52 | const [e164, setE164] = useState(""); 53 | 54 | 55 | {({ country, impossible, onBlur, onInputChange, inputValue }) => { 56 | return ( 57 | <> 58 |
59 | 63 | {country ? ( 64 | 69 | ) : ( 70 | <>✆ 71 | )} 72 | 73 | onInputChange(e.target.value)} 78 | /> 79 |
80 | {impossible && ( 81 |
Impossible phone number
82 | )} 83 | 84 | ); 85 | }} 86 |
; 87 | ``` 88 | 89 | [Demo][demo] 90 | 91 | ## Performance 92 | 93 | Due to this library's dependence on [libphonenumber-js], it clocks in at [38.7KB minified + gzipped][bundlephobia]. 94 | To improve your user's experience, react-headless-phone-component supports lazy loading with React Suspense with 95 | progressive auto-enachement. If your bundler supports dynamic imports and are using a compatible version of React, 96 | just swap `react-headless-phone-input` for `react-headless-phone-input/lazy`. 97 | 98 | Your UI will render and can be used immediately. Once `react-headless-phone-input` loads, the component will be 99 | automatically upgraded. No other changes are required. 100 | 101 | ```js 102 | import PhoneFormatter from "react-headless-phone-input/lazy"; 103 | ``` 104 | 105 | ## License 106 | 107 | [MIT](LICENSE) 108 | 109 | [falsehoods]: https://github.com/google/libphonenumber/blob/master/FALSEHOODS.md 110 | [libphonenumber-js]: https://www.npmjs.com/package/libphonenumber-js 111 | [tiny-flag-react]: https://github.com/benaubin/tiny-flag-react 112 | [bundlephobia]: https://bundlephobia.com/result?p=react-headless-phone-input 113 | [demo]: https://codesandbox.io/s/react-headless-phone-input-demo-ygow2?file=/src/App.js 114 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-headless-phone-input", 3 | "version": "3.0.0", 4 | "description": "A headless phone number input component", 5 | "type": "module", 6 | "main": "dist/index.umd.cjs", 7 | "module": "dist/index.js", 8 | "exports": { 9 | ".": { 10 | "import": "./dist/index.js", 11 | "require": "./dist/index.umd.cjs" 12 | }, 13 | "./lazy": { 14 | "import": "./dist/lazy.js" 15 | } 16 | }, 17 | "sideEffects": false, 18 | "scripts": { 19 | "storybook": "storybook dev -p 6006", 20 | "build-storybook": "storybook build" 21 | }, 22 | "peerDependencies": { 23 | "libphonenumber-js": "^1.10.38", 24 | "react": "^18" 25 | }, 26 | "devDependencies": { 27 | "@storybook/addon-essentials": "^7.1.1", 28 | "@storybook/addon-interactions": "^7.1.1", 29 | "@storybook/addon-links": "^7.1.1", 30 | "@storybook/addon-onboarding": "^1.0.8", 31 | "@storybook/blocks": "^7.1.1", 32 | "@storybook/react": "^7.1.1", 33 | "@storybook/react-vite": "^7.1.1", 34 | "@storybook/testing-library": "^0.2.0", 35 | "libphonenumber-js": "^1.10.38", 36 | "react": "^18", 37 | "react-dom": "^18", 38 | "storybook": "^7.1.1", 39 | "tiny-flag-react": "^2", 40 | "typescript": "*", 41 | "vite": "^4.4.7" 42 | }, 43 | "author": "Ben Aubin (benaubin.com)", 44 | "license": "MIT", 45 | "repository": { 46 | "type": "git", 47 | "url": "git+https://github.com/benaubin/react-headless-phone-input.git" 48 | }, 49 | "bugs": { 50 | "url": "https://github.com/benaubin/tiny-flag-react/issues" 51 | }, 52 | "homepage": "https://github.com/benaubin/tiny-flag-react#readme", 53 | "dependencies": { 54 | "vite-plugin-dts": "^3.4.0" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/PhoneFormatter.tsx: -------------------------------------------------------------------------------- 1 | import { AsYouType } from "libphonenumber-js/min"; 2 | import type { CountryCode } from "libphonenumber-js/min"; 3 | import React from "react"; 4 | 5 | /** Props for PhoneFormatter */ 6 | export interface PhoneFormatterProps { 7 | /** Changes will not affect the component after the first render */ 8 | readonly defaultCountry?: string; 9 | 10 | /** The phone number as E164 */ 11 | readonly value: string | undefined; 12 | 13 | /** Called with the E164 version of the phone number. */ 14 | onChange(v: string | undefined): void; 15 | 16 | children(data: { 17 | /** The formatted input value */ 18 | inputValue: string; 19 | onInputChange(newValue: string): void; 20 | 21 | /** The detected country of the number */ 22 | country?: string; 23 | /** 24 | * Result of a plausibility check: Is the phone number impossible? 25 | * 26 | * Prone to false negatives, but not false positives: 27 | * it may report an invalid phone number as possible 28 | */ 29 | impossible?: boolean | null; 30 | 31 | onBlur(): void; 32 | }): React.ReactNode; 33 | } 34 | 35 | 36 | /** 37 | * Headless phone number input formatter. 38 | */ 39 | export default function PhoneFormatter({ 40 | onChange, 41 | defaultCountry, 42 | ...props 43 | }: PhoneFormatterProps) { 44 | const [inputValue, setInputValue] = React.useState(""); 45 | 46 | const [formatter] = React.useState( 47 | () => new AsYouType(defaultCountry as CountryCode | undefined) 48 | ); 49 | 50 | const [impossible, setImpossible] = React.useState(null); 51 | 52 | const onInputChange = (newValue: string) => { 53 | if (inputValue == newValue) return; 54 | 55 | // The as-you-type formatter only works with append-only inputs. 56 | // Changes other than append require a reset. 57 | const isAppend = 58 | newValue.length > inputValue.length && 59 | newValue.slice(0, inputValue.length) == inputValue; 60 | 61 | if (isAppend) { 62 | const appended = newValue.slice(inputValue.length); 63 | setInputValue(formatter.input(appended)); 64 | } else { 65 | // Reset the formatter, but do not reformat. 66 | // Doing so now will cause the user to loose their cursor position 67 | // Wait until blur or append to reformat. 68 | formatter.reset(); 69 | formatter.input(newValue); 70 | setInputValue(newValue); 71 | } 72 | 73 | const number = formatter.getNumber(); 74 | 75 | const e164 = number?.number as string | undefined; 76 | onChange(e164); 77 | 78 | if (impossible && number && number.isPossible()) setImpossible(false); 79 | }; 80 | 81 | React.useLayoutEffect(() => { 82 | const number = formatter.getNumber()?.number; 83 | 84 | if (number != props.value) { 85 | // override the phone number if the field has a number and its e164 representation doesn't match the prop value. 86 | formatter.reset(); 87 | setInputValue(props.value ? formatter.input(props.value) : ""); 88 | 89 | const number = formatter.getNumber(); 90 | setImpossible(number == null ? null : !number.isPossible()); 91 | 92 | const e164 = number?.number as string | undefined; 93 | onChange(e164); 94 | } 95 | }, [props.value, formatter, inputValue, onChange]); 96 | 97 | const country = formatter.getNumber()?.country; 98 | 99 | return ( 100 | <> 101 | {props.children({ 102 | country, 103 | impossible, 104 | inputValue, 105 | onInputChange, 106 | onBlur() { 107 | const number = formatter.getNumber(); 108 | 109 | onChange(number?.number as string); 110 | 111 | if (!number) return setImpossible(null); 112 | 113 | // Check and update possibility 114 | const possible = number.isPossible(); 115 | setImpossible(!possible); 116 | 117 | if (possible) { 118 | // Reformat the phone number as international 119 | formatter.reset(); 120 | setInputValue(formatter.input(number.number as string)); 121 | } else { 122 | // Format the phone number 123 | setInputValue(formatter.input("")); 124 | } 125 | }, 126 | })} 127 | 128 | ); 129 | } 130 | -------------------------------------------------------------------------------- /src/as-you-type.cjs: -------------------------------------------------------------------------------- 1 | // A wrapped to import Libphonenumber.AsYouType by its default export to appease Webpack. 2 | import * as Libphonenumber from "libphonenumber-js/min/index.commonjs"; 3 | export const AsYouType = Libphonenumber.AsYouType; 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import PhoneFormatter from "./PhoneFormatter"; 2 | export type {PhoneFormatterProps} from "./PhoneFormatter"; 3 | export default PhoneFormatter; 4 | -------------------------------------------------------------------------------- /src/lazy.tsx: -------------------------------------------------------------------------------- 1 | import React, { lazy, Suspense } from "react"; 2 | import type { PhoneFormatterProps } from "./PhoneFormatter"; 3 | 4 | const PhoneFormatter = lazy(() => import("./PhoneFormatter")); 5 | 6 | /** 7 | * Lazy version of PhoneFormatter, using React.Suspense for progressive enhancement. 8 | */ 9 | export default function LazyPhoneFormatter(props: PhoneFormatterProps) { 10 | return ( 11 | 14 | {props.children({ 15 | inputValue: props.value || "", 16 | onInputChange(v) { 17 | props.onChange(v); 18 | }, 19 | onBlur() { 20 | /* no-op */ 21 | }, 22 | })} 23 | 24 | }> 25 | 26 | 27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /src/stories/story.stories.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import PhoneFormatter from "../lazy"; 3 | 4 | import TinyFlagReact from "tiny-flag-react/dist/index.js"; 5 | 6 | export default { title: "PhoneFormatter" }; 7 | 8 | export const demo = () => { 9 | const [number, setNumber] = useState(""); 10 | 11 | return ( 12 |
13 |

React Headless Phone Input Demo

14 | 15 |

e164: {number}

16 | 17 |
18 | 19 | {({ country, impossible, onBlur, onInputChange, inputValue }) => { 20 | return ( 21 | <> 22 |
23 | 27 | {country ? ( 28 | 33 | ) : ( 34 | <>✆ 35 | )} 36 | 37 | onInputChange(e.target.value)} 42 | /> 43 |
44 | {impossible && ( 45 |
Impossible phone number
46 | )} 47 | 48 | ); 49 | }} 50 |
51 |
52 | 53 |

54 | Works like a real input! Just with formatting. This example is set to 55 | use US phone numbers as a default. To enter an international number, use 56 | a country code. 57 |

58 | 59 |

Example phone numbers:

60 | 80 | 81 | 87 | 88 | 111 |
112 | ); 113 | }; 114 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "ESNext", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | "moduleResolution": "Bundler", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | // "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": true, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path' 2 | import { defineConfig } from 'vite' 3 | import dts from 'vite-plugin-dts' 4 | 5 | 6 | export default defineConfig({ 7 | build: { 8 | lib: { 9 | entry: [resolve(__dirname, 'src/index.ts'), resolve(__dirname, 'src/lazy.tsx')], 10 | name: 'index', 11 | }, 12 | rollupOptions: { 13 | // make sure to externalize deps that shouldn't be bundled 14 | // into your library 15 | external: ['react', 'libphonenumber-js'] 16 | }, 17 | }, 18 | plugins: [dts()] 19 | }) --------------------------------------------------------------------------------