Issue 8: front end nine inspiration sharing


Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing

1、 Set the verification of GIT commit(husky:^5Configuration before version is different from here)

In general, every time we executeGit commit - M 'submit information'The verification of commit information and code style will be triggered. If the verification fails, the commit will fail. How are these verifications added to the project?

Most of the time, we will use the verification for commithuskyLet’s install this package:

yarn add husky -D

In packae Add the following content to JSON, here is initialization Husky / directory and specify that the directory isgit hooksThe directory in which the so-calledgit hooksIt can be understood as the hook function of GIT, such asgit addBefore execution,git commitThen wait for the hook function of the life cycle, andgit hooksThe directory is used to definegitVarious functions that need to be executed in each life cycle.

  "scripts": {
    "prepare": "husky install"
Step 1: add code verification

Next, we execute on the command line:

yarn prepare
npx husky add .husky/pre-commit "npm run lint"

The second command above definespre-commitThis lifecycle is executednpm run lintThis command.

In packae Defined in JSONlintThe command is to useeslinttestingsrcThe files in the folder, of course, can detect any file.

  "scripts": {
    "lint": "eslint src"
Step 2: add submit information verification

CheckcommitThe easiest way for us to rely on information is to rely on itcommitlintThis bag.

yarn add @commitlint/config-conventional @commitlint/cli -D

New in root directorycommitlint.config.jsAnd write the following:

module.exports = { 
  extends: ["@commitlint/config-conventional"] 

Add a hook to verify the commit:

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

The above command means to create acommit-msgHook file, the content inside isnpx --no-install commitlint --edit "$1"

     commitlintCommand to detect$1Whether the value of this parameter is legal, and$1It’s oursgit commit -m ${1}

Calibration standard

     Please refer to the specification document

Here I only list the most commonly used:

standard Mode of use
docs Git commit - M "docs: update XXX document"
feat Git commit - M "feat: add XXX module"
fix Git commit - M "fix: fixed the Xbox bug on the line"
style Git commit - M "style: style of update user information pop-up"
test Git commit - M "test: modify the test case of adding user button"
Different from the configuration in your project?

Some students may find that my writing here may be inconsistent with that in your project. Your project may be written as follows:

  "husky": {
    "hooks": {
      "pre-commit": "npm run test",
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"

The above wording ishusky^6Before the version, nowhuskyIt has been updated to version 7, so it may not be configured in this way to create new projects in the future.

Git hook

Git official website description hooks

Issue 8: front end nine inspiration sharing

2、 / / / use of this annotation

We arereactThe following comments will be seen in the project code, so what are these strange comments for?

/// <reference types="react-scripts" />

So this///< reference types = "package" / >Is mainly used in.d.tsIn the file, the function is to introduce other.d.tsFile, for example, I need to use onexxx.d.tsFile, but this is not innode_modules/@typesInside, so it will not be imported by the system by default.

Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing

Explanation given on TS official website

3、 Recommend onereactBoot plug-inguide

Plug in address

Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing

Generally, there will be a guidance operation when the website is visited for the first timeguideIt can be easily implemented. Let’s configure it step by step:

yarn add byte-guide

The central idea of using this plug-in is that we pass in a set of configurations in the form of an array and find a configuration withTo be mountedThe target dom of the array, as well as the displayed copy and other information, and then each time you click next, you can execute the objects in the array in turn:

import Guide from "byte-guide";

export default function Home() {
  const SEARCH = {
    hotspot: true,
    Title: "search component",
    selector: "#search",
    placement: "top-left",
    Content: < div > this search component is very powerful < / div >,
    offset: { x: 20 },
  const TOTAL = {
    Title: "total number of lists",
    parent: "#search",
    selector: "#total",
    placement: "right",
    Content: "here is the total number of lists.",

  return (
    <div className={"org"}>
      < div id = {"search"} > target 1 < / div >
      < div id = {"total"} > goal 2 < / div >
        steps={[SEARCH, TOTAL]}
        onClose={() => {
          console. Log ("click Close");
        afterStepChange={(nextIndex, nextStep) => {
          console. Log ("click Next");
Description of main attributes
  1. localKey: the display of our boot component is usually displayed only when the user logs in for the first time, or it will never be displayed when the user clicks the end button of boot,guideStore the value of whether to display the boot component in theLocal StorageTherefore, the stored key name is defined here.
  2. placementDefines the location of the pop-up box, such as the top element. We will choose to use itbottomProperties like.
  3. offsetAlthough it is setplacementHowever, it is inevitable that the position is unsatisfactory, so you can use this attribute to readjust the position of the boot box.
matters needing attention

The component has built-in simple internationalization, that is, when we do not specify a copy, it will be based on the incoming languageEnglishchineseJapaneseMake copywriting changes.

There is a bug in this plug-in. If two elements are in the internal scrolling state of the parent element, there will be many positioning errors. Therefore, if your boot project involves internal scrolling elements, it is not recommended to use this plug-in.

4、 Comments can be made after eslint 7

It is found that some problems are inevitable in team projects/* eslint-disable*/Each time we see this annotation, we will try to delete it, but it may cause a series of chain translations. In this case, if we useeslint^7Version and above, you can add notes to explain why it must be used here/* eslint-disable*/

//Eslint disable next line a-rule -- the error here cannot be repaired!

The above wording is more friendly because, after all, this prohibitioneslintThe detection method is not recommended for everyone. If it must be used, it is also necessary to indicate the reason at the initial stage.

5、 Advantages and disadvantages of unifying the export of an index file

For example, we have manyTool methodIn the same folder,a.jsFile exporta1, a2We often use oneindex.jsFiles are exported uniformly. There are many ways to write them in the project:

export * from './a';

export * from './b';

export * from './c';

export * from './d';

Although this way of writing seems to care about “elegance”, there are many disadvantages. Here are some examples:

1: Export name may be duplicate

This is a small problem because there will betsError prompt, the cause isindex.jsThere is no specific method name written in the file, so you need to pay attention to whether the index file reports an error every time you modify it.

2: Code routing trouble

This is the most unfriendly point to the operation. For example, we have an external import method on a page. If we use a Mac computer, click ` C
Command + left mouse buttonYou can find the source of this method, but it is often only foundindex. JS’, there is no specific method name here, so you need to query in each file again.

3: No prompt for changing export

When we modify an export, there is no prompt, such as deleting an export method and modifying the name of an export method. At this time, it will not be displayed in the file itself andindex.jsAn error is reported in a file. The error is reported in the specific file using this method, which may be ignored because the project is not started directlygit pushIt can also pass the test.

4: TS type quadratic derivation

Sometimes you name and export a method function, but eslint reports an errorThe member was not exportedHowever, when we enter the folder of this method, the error reported by eslint disappears. This bad experience is related to this writing method.

VisvgrLibrary conversionSvg picture, filter:drop-shadow

     xxx.svgThese files are not easy to control. We want to dynamically pass in many configurations, which may need helpsvgrThis library willSvg pictureconvert toreactIn the form of component, code data can be generated on the command line through the following command:

NPX @ svgr / cli -- address of icon picture svg

Issue 8: front end nine inspiration sharing

Generation on the command line is definitely not engineering. In fact, this has been built into various scaffoldssvgrLibrary, so we can actually use it in the following waysComponent modeSvg pictures.

import { ReactComponent as Logo } from "./logo.svg";

// ....

<Logo width={"30px"} style={{ filter: "drop-shadow(red 20px 0)" }} />  

     filter: "drop-shadow(red 20px 0)"This sentence can make SVG turn red. I’ll take a separate article on its details.

7、 Yarn solutions manages packages that are dependent on multiple projects

Many NPM packages will be referenced in the project. For example, we rely on them in the projectPackage a, Package aSelf dependence^3.1.5VersionPackage B, we the project itselfyarn add BAlready installed^3.0.5VersionPackage B, at this timePackage BIn fact, it can be used in general. There is no need to reference two versions.

And if it is packaged, due to the different versions we rely onPackage BIt leads to the increase of volume after packaging, soyarnProvidedresolutionsThis configuration item can be configured as follows (package. JSON):

  "resolutions": {
    "B": "^3.1.5"
Take a practical example
We create a new project
NPX create react app project name

Enter into the project

yarn list --depth=1

List the dependencies of the project and print only one level of dependency. We willworkbox-buildFor example:
Issue 8: front end nine inspiration sharing

We’re in the outer layerpackage.jsonConfigure:

  "resolutions": {
    "fs-extra": "^4.0.2"

Execute at this timeyarnCommand, and hereyarn list --depth=1Print:

Issue 8: front end nine inspiration sharing

The above dependencies have changed, not just inworkbox-buildUnder the bag.

8、 Pnpm replaces yarn lean for package management

We often useyarn + leanSubprojects are managed this way, but are in transitpnpmMore suitable for this job, so whypnpmBetter for that?

     yarnAdministrationnode_modulesThe mechanism will lead to,Package aDependentPackage B, thenPackage BThe file location will be in the same location asPackage aAt the same level, which leads to developers who do not executeyarn add BHowever, it can also be introduced into the projectimport B from 'B'This is a hidden danger for development.

     pnpmIn this way, the package is managed uniformly and the cost of a single project is reducednode_modulesSimilar to those stored in the fileSoft connectionIn this way, there will be no repeated installation of a dependency, and there is no need toB and aAt the same level, there will be no inexplicable introductionPackage B

When we have many subprojects and dependencies become more and more complex,pnpmThe advantages of are shown.

9、 How to start the sub application of the micro front end separately

There are several subprojects in micro front-end applications. These subprojects often rely on a main project (Shell project), which is responsible for distributing some reused resources, such asreact react-routerAnd other public dependencies, and there will also be some custom dependencies in the main projectutilsTool method passed toSubproject

Since there are many resources that need to be distributed by the main project, it is difficult for the sub project to run alone. We have to start at least every timeMain project + sub projectAnd to see the complete project, you need to start all the restSubprojectBut what can we do to start only the subproject itself?

My approach here is to use the request proxy, because the principle of most micro front-end frameworks isEach subprojectIt’s all oneJS file, load on demand after the main application startsJS entry file of subprojectThen we can visitOnline test environmentAnd find the addressOnline test environmentThe primary application accesses the child applicationurlAnd then put thisurlThe agent points to a locally startedSubprojectJust click your address.

The advantage of this is that the subprojects can be completely in the context of the main application of an online environment, and there is no need to start other subprojects. Pay attention to the of subprojectscssDocuments should also be represented.


This is it. I hope to make progress with you.