开源软件名称(OpenSource Name):alexeagleson/template-react-component-library开源软件地址(OpenSource Url):https://github.com/alexeagleson/template-react-component-library开源编程语言(OpenSource Language):TypeScript 69.1%开源软件介绍(OpenSource Introduction):React Component Library TemplateThis project is part of a blog & video tutorial on how to create and publish your own component library. You can use this repo to fork as a template for your own React library projects. Available ScriptsBuild the library
Publish the library
Run tests
Run storybook locally
Build storybook
Tutorial
IntroductionThis tutorial will take you through the process of creating and publishing your own custom React component library and hosting it on Github. At the end of this tutorial you will have the ability to the following in all of your future React projects: npm install @my-github-account/my-cool-component-library import MyCustomComponent from '@my-github-account/my-cool-component-library';
const MyApp = () => {
return (
<div>
<MyCustomComponent />
</div>
)
} Prerequisites and SetupThis project assumes you are familiar with and have installed:
First we will initialize our project. npm init You can take the defaults for all the values, we'll edit them later in the tutorial. Next we will add add the tools necessary to create our components. npm install react typescript @types/react --save-dev Creating ComponentsNow we can create our first component. Because we are creating a library, we are going to create index files for each tier, and export our components from each one to make it as easy as possible for the people using our library to import them. Within the root of your project, create the following file structure:
Make sure to double check your structure. You should have three Begin by creating
import React from "react";
export interface ButtonProps {
label: string;
}
const Button = (props: ButtonProps) => {
return <button>{props.label}</button>;
};
export default Button; To keep things simple we will just export a button that takes a single prop called After our button, we update the index file inside our Button directory:
export { default } from "./Button"; Then we export that button from the components directory:
export { default as Button } from "./Button"; And finally, we will export all of our components from the base src directory:
export * from './components'; Adding TypescriptUp until now, we haven't yet initialized Typescript in our project. Although you technically don't need a configuration file to use Typescript, for the complexity of building a library we are definitely going to need one. You can initialize a default configuration by running the following command: npx tsc --init That will create a If you would like to learn more about the many options in a You may notice depending on your IDE that immediately after initializing you begin to get errors in your project. There are two reasons for that: the first is that Typescript isn't configuration to understand React by default, and the second is that we haven't defined our method for handling modules yet: so it may not understand how to manage all of our exports. To fix this we are going to add the following values to {
"compilerOptions": {
// Default
"target": "es5",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
// Added
"jsx": "react",
"module": "ESNext",
"declaration": true,
"declarationDir": "types",
"sourceMap": true,
"outDir": "dist",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"emitDeclarationOnly": true,
}
} I have separated these values into a couple different sections based on the default The values marked added are new values that we need for our project. We'll briefly outline why we need them:
One you add those values to your TS configuration file you should see the errors in Adding RollupNext we will add rollup to our project. If you've never used rollup before, it's very similar to webpack in that it is a tool for bundling individual Javascript modules into a single source that a browser is better able to understand. Though both tools can accomplish the same goal depending on configuration, typically webpack is used for bundling applications while rollup is particularly suited for bundling libraries (like ours). That's why we've chosen rollup. Also similar to webpack, rollup uses a plugin ecosystem. By design rollup does not know how to do everything, it relies on plugins installed individually to add the functionality that you need. We are going to rely on four plugins for the initial configuration of our library (more will be added later):
So with that said, let's go ahead and install rollup and our plugins: npm install rollup @rollup/plugin-node-resolve @rollup/plugin-typescript @rollup/plugin-commonjs rollup-plugin-dts --save-dev To configure how rollup is going to bundle our library we need to create a configuration file in the root of our project:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
const packageJson = require("./package.json");
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
],
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
},
]; In this file we import our four plugins that we installed. We also import our The entrypoint for our library (input) is the The second configuration object defines how our libraries types are distributed and uses the The final step before we can run our first rollup is to define the values of "main" and "module" in our
{
"name": "template-react-component-library",
"version": "0.0.1",
"description": "A simple template for a custom React component library",
"scripts": {
"rollup": "rollup -c"
},
"author": "Alex Eagleson",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-node-resolve": "^13.0.6",
"@rollup/plugin-typescript": "^8.3.0",
"@types/react": "^17.0.34",
"react": "^17.0.2",
"rollup": "^2.60.0",
"rollup-plugin-dts": "^4.0.1",
"typescript": "^4.4.4"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"files": [
"dist"
],
"types": "dist/index.d.ts"
} Here is the sample of the The most important changes are as follows:
Building your libraryWith these configurations in place you are now ready to run rollup for the first time and make sure your basic configuration is correct. Your project structure should look like this before you run:
The contents of each file should be as described above. Once you have confirmed this, run the following command: npm run rollup If everything has been configured correctly rollup will run without error and you will see a (If you received an error make sure to read it closely to try and identify the issue. Double check that each of your files follows exactly the structure of the examples. Depending on the amount of time passed since the publishing of this tutorial, new major versions of libraries could potentially be published with breaking changes. All versions of libraries numbers are visible above in the Publishing your libraryNow that we've created our component library, we need a way to allow ourselves (or others) to download and install it. We will be publishing our library via NPM through hosting on Github. First before anything else we need to create a repository for our library. Create a new repository on Github. I have titled mine Log into Github and create a new repository called whatever you like. For this example I've titled it Once the repository is created we need to initialize git within our project locally. Run the following command:
Next create a
In our Now follow the instructions on Github shown in your new repository for committing your code. This repository that you have created is the one you will clone & edit when you want to make changes and updates to your component library. This is not the package itself that your (as a user) would install and use. To configure within our project where our package needs to be published to, next we need to update
You will be updating the field "name" value and adding a new field called "publishConfig". Note the values above in caps are meant to be replaced with your own values. For example my "name" field value would be Now that we have configured out project, we need to configure our local install of NPM itself to be authorized to publish to your Github account. To do this we use a This file is NOT PART OF OUR PROJECT. This is a global file in a central location. For Mac/Linux users it goes in your home directory For Windows users it goes in your home directory as well, though the syntax will be different. Something along the lines of For more information about this configuration file read this. Once you have created the file, edit it to include the following information:
There are two values in caps to replace in the example above. The first is YOUR_GITHUB_USERNAME. Make sure to include the leading @ symbol. The second is YOUR_AUTH_TOKEN which we haven't created yet. Back to Github! Go to your Github profile: Settings -> Developer Settings -> Personal access tokens. Or just click this link Click Generate new token. Give it a name that suits the project you are building. Give it an expiry date (Github recommends you don't create tokens with an infinite lifespan for security reasons, but that's up to you). The most important thing is to click the Once you are done you can click to create the token. Github will ONLY SHOW YOU THE TOKEN ONCE. When you close/refresh the page it will be gone, so make sure to copy it to a secure location (perhaps a password manager if you use one). The main location you need to place this token is in the Before you continue, do one more sanity check to be sure you didn't create the At this point, once you npm publish (If you get prompted for login credentials, the username is your Github username and your password is the access token you generated) Congratulations! You have now published version 0.0.1 of your React component library! You can view it on your Github account by going to your main account dashboard and clicking "packages" along the top to the right of "repositories":: Using Your LibraryNow that your library is live, you'll want to use it! Note that the instructions for using your library are slightly different if you published to a private repository. Everyone (aside from your own machine) who tries to import it is going to get a 404 Not Found error if they are not authorized. Those users also need to add a (From this point onward we will presume you have completed that step, or are working with a public repository.) Since we have created a component library using React and Typescript, we are presuming that the consumers of our library will be using those tools as well. Technically all of our type files For our example we will use it however so that we can confirm that they are working properly. We will initialize a React app using one of the most popular and simple methods: Create React App. Run the following command in a new directory: (Remember we are simulating other users downloading and installing our library, so this project should be completely separate from the library itself) npx create-react-app my-app --template typescript Open the new npm run start Confirm that you are able to open and load the default application screen on Now comes the test for our library. From the root directory of your new npm install @YOUR_GITHUB_USERNAME/YOUR_REPOSITORY_NAME So for my project for example its: Presuming your tokens and configuration are set up properly, everything will install correctly (if there are any issues, revisit the example for the Now open the When you go to add a Lets add it! The simplest example to update
import React from "react";
import { Button } from "@alexeagleson/template-react-component-library";
function App() {
return <Button label="Hello world!"/>;
}
export default App; And when we run And that's it! Congratulations! You now have all the tools you need to create and distribute a React component library using Typescript! At this point you end the tutorial and continue on your own if you wish. If you choose to continue, we will look at how to expand our component library to include a number of extremely useful features such as:
Adding CSSBefore we do any additional configuration, we'll begin by creating a CSS file that will apply some styles to our Button. Inside of the
button {
font-size: 60px;
} This will turn our regular Hello world! button into a REALLY BIG button. Next we will indicate that these styles are meant to be applied on our button component. We'll be using special syntax that isn't native to Javascript, but thanks to rollup and the appropriate plugins, we are able to use it. Update our
import React from "react";
import "./Button.css";
export interface ButtonProps {
label: string;
}
const Button = (props: ButtonProps) => {
return <button>{props.label}</button>;
};
export default Button; Notice the Now we need to tell rollup how to process that syntax. To do that we use a plugin called npm install rollup-plugin-postcss --save-dev Next we need to update our rollup config:
全部评论
专题导读
上一篇:krishrahul98/DSA-Library: Collection of all important Data Structures and algori ...发布时间:2022-08-15下一篇:bitcoinj/bitcoinj: A library for working with Bitcoin发布时间:2022-08-15热门推荐
热门话题
阅读排行榜
|
请发表评论