{"id":19129230,"url":"https://github.com/ananduremanan/custom-react-npm-module","last_synced_at":"2025-05-06T00:14:13.551Z","repository":{"id":155939423,"uuid":"626735829","full_name":"ananduremanan/custom-react-npm-module","owner":"ananduremanan","description":"This repo helps to create a React.js component as a local npm module, and it can be used in other projects using npm install.","archived":false,"fork":false,"pushed_at":"2024-06-02T08:50:15.000Z","size":11985,"stargazers_count":30,"open_issues_count":0,"forks_count":8,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-06T00:14:05.425Z","etag":null,"topics":["babel","npm-module","reactjs-components","rollup","typescript","typescriptreact"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ananduremanan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-04-12T04:01:11.000Z","updated_at":"2025-03-29T12:26:54.000Z","dependencies_parsed_at":"2024-06-10T19:45:47.759Z","dependency_job_id":null,"html_url":"https://github.com/ananduremanan/custom-react-npm-module","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ananduremanan%2Fcustom-react-npm-module","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ananduremanan%2Fcustom-react-npm-module/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ananduremanan%2Fcustom-react-npm-module/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ananduremanan%2Fcustom-react-npm-module/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ananduremanan","download_url":"https://codeload.github.com/ananduremanan/custom-react-npm-module/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252596429,"owners_count":21773846,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["babel","npm-module","reactjs-components","rollup","typescript","typescriptreact"],"created_at":"2024-11-09T06:06:54.428Z","updated_at":"2025-05-06T00:14:13.531Z","avatar_url":"https://github.com/ananduremanan.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# How to create a Custom NPM Module with React Components?\n\nThis repo is aimed to describe the process of creating a custom NPM package/module with React.JS components. It will guide you through the steps of setting up your development environment, writing and exporting your components, and publishing your package to the NPM registry[Optional]. Additionally, it will provide tips and best practices for maintaining and updating your package.\n\n## Installation\n\n**Step 1:** Make a directory and initialize npm.\n\n```bash\n  mkdir custom-npm-package\n  npm init\n```\n\nAlternatively, you can use the following command to quickly generate a minimal boilerplate:\n\n```bash\nnpm init -y\n```\n\nAdd the necessary fields. After the successfull walkthrough a package.json will created and looks like below.\n\n```bash\n{\n  \"name\": \"gittuts\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}\n```\n\n**Step 2:** Create a src folder in the root add a index.js/index.ts in it also create a component folder and creates some components in it.\n\n```bash\nsrc\n├── components\n│   ├── Component1\n│   │   └── index.tsx\n│   ├── Component2\n│   │   └── index.tsx\n│   └── Component3\n│       └── index.tsx\n└── index.ts\n```\n\n**Step 3:** Now, Add react and react-dom as peer-dependencies and dev-dependencies. \n\n```bash\n  yarn add react react-dom --dev\n\n  or\n\n  npm install react react-dom --dev\n```\n\nThe final package.json may looks like below.\n\n```bash\n  {\n  \"name\": \"custom-npm-package\",\n  \"version\": \"1.0.0\",\n  \"description\": \"react custom npm module\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"build\": \"npx babel src --out-file index.js --extensions .ts,.tsx\"\n  },\n  \"author\": \"Anandhu\",\n  \"license\": \"ISC\",\n  \"peerDependencies\": {\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^18.0.34\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"typescript\": \"^5.0.4\"\n  }\n}\n```\n\nSince it is Typescript. I've also installed typescript, typescript react with it.\n\n**Step 4:** Its time to bundle the code. Install [rollup.js](https://rollupjs.org/)\n\n```bash\n  npm install --save react rollup\n```\nYou will also need to install the Rollup plugins for Babel, CommonJS, and Node Resolve by running \n\n```bash\nnpm install --save-dev @rollup/plugin-babel @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-terser\n\n```\n\n**Step 5:**  Configure Rollup\n\nCreate a `rollup.config.mjs` or `rollup.config.js` file in the root of your project. In this file, configure Rollup to bundle your React component by specifying the input file, output format, and plugins to use. Here is an example configuration:\n\n```bash\nimport babel from 'rollup-plugin-babel';\nimport resolve from '@rollup/plugin-node-resolve';\nimport external from 'rollup-plugin-peer-deps-external';\nimport terser from '@rollup/plugin-terser';\nimport typescript from \"rollup-plugin-typescript2\"; // For Typescript\n\nexport default [\n  {\n    input: './src/index.ts',\n    output: [\n      {\n        file: 'dist/index.js',\n        format: 'cjs',\n      },\n      {\n        file: 'dist/index.es.js',\n        format: 'es',\n        exports: 'named',\n      }\n    ],\n    plugins: [\n      babel({\n        exclude: 'node_modules/**',\n        presets: ['@babel/preset-react']\n      }),\n      external({\n        includeDependencies: true\n      }),\n      resolve(),\n      terser(),\n      typescript({ useTsconfigDeclarationDir: true }),\n    ]\n  }\n];\n\n```\n\nTo our package.json, let's add this as build command so that we won't have to type it repeatedly. Under \"scripts\" in package.json add the following.\n\n```bash\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"build\": \"npx rollup -c\"\n  }\n```\n\nnow we can simply use ```npm run build``` or ```yarn build``` to bundle the code.\n\nIf it compiled without any error you may see a new folder `dist` generated in the root folder with transpiled Javascript Code.\n\n![App Screenshot](https://github.com/ananduremanan/Demo/blob/main/Screenshot%202023-12-12%20153616.png)\n\n_image: bundled output_\n\nNote: that if you're using a build tool like Webpack, you may not need to use npx babel at all. Instead, you can use a TypeScript loader like ts-loader or awesome-typescript-loader that will transpile and transform your TypeScript files as part of the build process.\n\n**Step 6:** Lets pack it so we can use/test it in other projects. Run the following command from  the root folder.\n\n```bash\n  npm pack\n```\nThis will generate a .tgz file that we can use to install the package locally in other projects.\n\nAlternatively, you can link the package for testing purpose(Recommended).\n\nUsing `npm link` in your package's root directory, create a global symlink of your package. A shortcut that directs your system to another directory or file is known as a \"symlink,\" short for symbolic link.\n\nNow, create an another application and tell the application to use the global symlink with `npm link your-package-name`. This way, we could save a lot of time.\n\n**Step 7:** Navigate to your other project's directory and install your package using npm install \u003cpath to tarball file\u003e. For example:\n\n```bash\n  npm i 'path_to_the_packed_file'\n```\n\n**Step 8:** In your host project's code you can import and use your component as follows:\n\n```bash\n  import logo from \"./logo.svg\";\n  import \"./App.css\";\n  import TextInput from \"my_npm_package\"; // Importing from the package\n  import { useState } from \"react\";\n\n  function App() {\n    const [value, setValue] = useState('');\n    console.log(value)\n\n    function handleChange(e) {\n      setValue(e.target.value);\n    }\n\n    return (\n      \u003cdiv className=\"App\"\u003e\n        \u003cheader className=\"App-header\"\u003e\n          \u003cimg src={logo} className=\"App-logo\" alt=\"logo\" /\u003e\n          \u003cp\u003eCustom npm module.\u003c/p\u003e\n          \u003cTextInput label=\"Name\" value={value} onChange={handleChange} /\u003e\n        \u003c/header\u003e\n      \u003c/div\u003e\n    );\n  }\n\n  export default App;\n\n```\n\nAdditionally we can use packages like [storybook.js](https://storybook.js.org/) to build UI components and pages in isolation and by doing so we could see the changes that happens to our components without the need of installing it in a host application. You could find the documention for implementing story book [here](https://storybook.js.org/docs/react/get-started/install/).\n\n**Step 9:** Publishing our package to NPM Registry\n\nTo publish a package to the npm registry, we need to follow these steps:\n\n- Create an npm account on [npmjs.com](https://www.npmjs.com/signup).\n- Sign in to npm from your terminal using the ```npm login``` command.\n- Prepare your package for publishing.\n- Publish the package from the terminal using the ```npm publish``` command.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fananduremanan%2Fcustom-react-npm-module","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fananduremanan%2Fcustom-react-npm-module","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fananduremanan%2Fcustom-react-npm-module/lists"}