Install React with the help of 🔥 Webpack | Vite | Snowpack

Project address github.com/LuckyChou71…

Eslint | prettier where VScode is needed

Time machine 👾

  • React Volume | JSX ✅ ✅

  • React Volume | Set sail basic grammar ✅ ✅

  • React. Hooks ✅ ✅

  • React Volume | CSS Solution ✅ ✅

  • React Volume | Old and new life cycle ✅ ✅

  • React Volume | State Management Redux ✅ ✅

  • React Volume | State Management Redux Middleware ✅ ✅

  • React Volume | State Management Mobx

  • React Volume | Route Management ✅ ✅

  • React Brochure | Webpack | Vite | Snowpack ✅ ✅

  • React Volume | SSR

  • React Volume | React Recommendations ✅ ✅

Webpack

typescript

Install typescript and TS-Loader

The latter is used as a loader for webpack to convert TS -> JS

After installation, use TSC –init to generate the tsconfig.json file

I have turned on some of the configurations here. For details about each configuration, please refer to the official documentation

Aka. Ms/tsconfig. Js…

{
  "include": ["src"."types"] / * * /."exclude": ["node_modules"]."compilerOptions": {
    "target": "ESNEXT" /* Direct output to the latest ES standard */."module": "ESNEXT" /* Future ESM modularity */."lib": ["DOM"."DOM.Iterable"."ESNext"]."allowJs": false /* Not allowed to import js files */."jsx": "react-jsx" /* select this after react17 */."outDir": "./build" /* Package path */."strict": true /* Enable strict mode */."noImplicitAny": true /* Cannot use any */."moduleResolution": "node" /* We use node */ here."baseUrl": ". /" /* Configures the root path such as the following typeRoots and top include exclude to include this path */."typeRoots": [
      "node_modules/@types"."types/*.d.ts"
    ] /* The type declaration file can be configured to add some of your own types */."allowSyntheticDefaultImports": true /* The default import can be used even if a module does not have one."esModuleInterop": true /* https://zhuanlan.zhihu.com/p/148081795 */."experimentalDecorators": true /* Open decorator syntax */."skipLibCheck": false /* Skip type checking for all.d.ts files */."forceConsistentCasingInFileNames": true}}Copy the code

Let’s create a new types directory that defines the types we want to define for example

/* Use this file to declare any custom file extensions for importing */
/* Use this folder to also add/extend a package d.ts file, if needed. */

/* CSS MODULES */
declare module '*.module.css' {
  const classes: { [key: string] :string };
  export default classes;
}
declare module '*.module.scss' {
  const classes: { [key: string] :string };
  export default classes;
}
declare module '*.module.sass' {
  const classes: { [key: string] :string };
  export default classes;
}
declare module '*.module.less' {
  const classes: { [key: string] :string };
  export default classes;
}
declare module '*.module.styl' {
  const classes: { [key: string] :string };
  export default classes;
}

/* CSS */
declare module '*.css';
declare module '*.scss';
declare module '*.sass';
declare module '*.less';
declare module '*.styl';

/* IMAGES */
declare module '*.svg' {
  const ref: string;
  export default ref;
}
declare module '*.bmp' {
  const ref: string;
  export default ref;
}
declare module '*.gif' {
  const ref: string;
  export default ref;
}
declare module '*.jpg' {
  const ref: string;
  export default ref;
}
declare module '*.jpeg' {
  const ref: string;
  export default ref;
}
declare module '*.png' {
  const ref: string;
  export default ref;
}

/* CUSTOM: ADD YOUR OWN HERE */
Copy the code

webpack

Install webpack webpack-cli webpack-dev-server

  • Webpack Core Functions of Webpack

  • Webpack -cli Webpack command line

  • The Webpack-dev-server development environment is easy to use and debug

Then create a new Config folder to write the webPack configuration file

We created our own configuration files for development and production as webpack.config.dev.js and webpack.config.prod.js respectively

Because THE CSS in the project uses SCSS, I need to install sass sass-loader in advance

There are also htML-webpack-plugin and clean-webpack-plugin required for the build

webpack.config.dev.jsIs configured as follows

const path = require('path');
// Generate HTML files automatically import packaged JS files
const HtmlWebpackPlugin = require('html-webpack-plugin');

const htmlWebpackPlugin = new HtmlWebpackPlugin({
  template: path.resolve(__dirname, '.. /public/index.html')});module.exports = {
  mode: 'development'.entry: path.resolve(__dirname, '.. /src/index.tsx'),
  output: {
    path: path.resolve(__dirname, '.. /build'),
    filename: 'js/[name].[hash].bundle.js',},module: {
    // Since we are a TS project, we can compile files to JS directly with ts-loader without using Babel translation
    rules: [{test: /\.tsx? $/,
        use: 'ts-loader'.exclude: /node_modules/,},// Configure the SCSS environment ⚠️ Notice Loader is used from right to left
      // So the sequence is ass-loader --> CSS-loader --> style-loader
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Generate JS strings as style nodes
          'style-loader'.// Convert CSS to CommonJS modules
          'css-loader'.// Compile Sass to CSS
          'sass-loader',],},],},plugins: [htmlWebpackPlugin],

  resolve: {
    extensions: ['.tsx'.'.ts'.'.js'],}};Copy the code

webpack.config.prod.jsConfiguration is as follows

const path = require('path');
// Generate HTML files automatically import packaged JS files
const HtmlWebpackPlugin = require('html-webpack-plugin');
// Clean up the bundle.js folder before packaging. Since the packaged files will not have the same hash names, they will not be overwritten multiple times
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const htmlWebpackPlugin = new HtmlWebpackPlugin({
  template: path.resolve(__dirname, '.. /public/index.html')});module.exports = {
  mode: 'production'.entry: path.resolve(__dirname, '.. /src/index.tsx'),
  output: {
    path: path.resolve(__dirname, '.. /build'),
    filename: 'js/[name].[hash].bundle.js',},module: {
    rules: [{test: /\.tsx? $/,
        use: 'ts-loader'.exclude: /node_modules/}, {test: /\.s[ac]ss$/i,
        use: [
          // Generate JS strings as style nodes
          'style-loader'.// Convert CSS to CommonJS modules
          'css-loader'.// Compile Sass to CSS
          'sass-loader',],},],},plugins: [htmlWebpackPlugin, new CleanWebpackPlugin()],

  resolve: {
    extensions: ['.tsx'.'.ts'.'.js'],}};Copy the code

Our Prod has only one more clean-webpack-plugin configuration than Dev’s because there are not many scenarios involved

You can also use the webpack-Merge library to extract some common configurations

Github.com/survivejs/w…

eslint

Eslint verifies that our code generates a uniform style

Install ESLint first and then generate the esLint configuration using ESLint –init

Here are some of the authors’ choices

? How would you like to use ESLint? ... To check syntax only To check syntax and find problems ❯ To check syntax, find problems, and Enforce code style? Whattypeof modules does your project use? ... ❯ JavaScript modules (import /export) CommonJS (require/exports) None of these ? Which framework does your project use? ... ❯ React vue.js None of these? Does your project use TypeScript? ❯ Yes No? Where does your code run? ... (Press <space> to select, <a> to toggle all, < I > to invert Selection) ❯ Browser Node? How would you like to define a styleforyour project? ... ❯ Use a popular style guide Answer questions about your style Inspect your JavaScript file(s)? Which style guidedoyou want to follow? ... ❯ reality: https://github.com/airbnb/javascript Standard: https://github.com/standard/standard Google: https://github.com/google/eslint-config-google XO: https://github.com/xojs/eslint-config-xo ? What formatdo you want your config file to be in? ... ❯ JavaScript YAML JSON Would you like to install them now with NPM? ❯ Yes NoCopy the code

This will generate an.eslintrc.js file in the root directory of the project that looks like this

module.exports = {
  env: {
    browser: true.es2021: true,},extends: ['plugin:react/recommended'.'airbnb'].parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaFeatures: {
      jsx: true,},ecmaVersion: 12.sourceType: 'module',},plugins: ['react'.'@typescript-eslint'].rules: {}};Copy the code

The dependencies added after the above operations are attached

"@typescript-eslint/eslint-plugin": "^4.31.2", "@typescript-eslint/parser": "^4.31.2", "eslint": "^ 7.32.0 eslint - config -", "reality", "^ 18.2.1", "eslint - plugin - import" : "^ 2.24.2", "eslint - plugin - JSX - a11y" : "^ 6.4.1 eslint", "- the plugin - react" : "^ 7.26.0", "eslint - plugin - react - hooks" : "^ 4.2.0"Copy the code

prettier

Installing PretTier Creating a new prettier.config.js file Here are some of my configurations

module.exports = {
  printWidth: 100.// Single line length
  tabWidth: 2.// Indent length
  useTabs: false.// Use Spaces instead of TAB indentation
  semi: true.// Use a semicolon at the end of a sentence
  singleQuote: true.// Use single quotes
  quoteProps: 'as-needed'.// Add quotes to the key of the object only when necessary
  jsxSingleQuote: true.// JSX uses single quotes
  trailingComma: 'all'.Print trailing commas if possible for multiple lines
  bracketSpacing: true.// Add Spaces before and after the object -eg: {foo: bar}
  arrowParens: 'always'.// Use parentheses around the arguments of the single-argument arrow function -eg: (x) => x
  requirePragma: false.// Format without top comments
  insertPragma: false.// Add a note at the top of the file where prettier had been formatted
  htmlWhitespaceSensitivity: 'ignore'.// Not sensitive to HTML global whitespace
  endOfLine: 'lf'.// End the line form
  embeddedLanguageFormatting: 'auto'.// Format the reference code
};
Copy the code

A script command is then written

"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\""
Copy the code

Execute this command to format all code according to the above rules

Here we finish the basic configuration and then install the necessary React React -dom

Then create the following project directory

├─ ├─ webPack.config.dev.js │ ├─ webpack.config.js │ ├─ webpack.config.js │ ├─ webpack.config ├─ public │ ├─ index.html │ ├─ SRC │ ├─ webPack.config.js ├─ package.json ├─ public │ ├─ index.html │ ├─ SRC │ ├─ App. The module. SCSS │ ├ ─ app. The TSX │ └ ─ index. The TSX ├ ─ tsconfig. Json ├ ─ types │ └ ─ static. Which s └ ─ yarn. The lockCopy the code

FAQ

And then ridiculous things happen when you don’t even start the project

Cannot find module ‘./app.module.scss’ or its corresponding type declarations.

The reason is simple: TS cannot treat app.module. SCSS as a module

And we didn’t write a type declaration file for it

There are two ways to solve this

The first is to write a.d.ts declaration file for each SCSS file

For example, our app.module. SCSS has the following content

.container {
  color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 66px;
  height: 90vh;
}
Copy the code

We could write an app.module.scs.d. ts file declaring the type for each selector

export const container: string;
Copy the code

This eliminates the error and provides a friendly code prompt when introduced

The second is to write a global declaration file for the SCSS file. We created the types file in the TS section above

It contains our definitions of SCSS files

We just need to configure typeRoots in tsconfig.json and add our types

"typeRoots": ["node_modules/@types", "types/*.d.ts"]
Copy the code

eslint

Eslint also has a lot of incompatibilities

For example, our project is React17 and we don’t have to introduce React anymore but ESLint will report an error

And then some of the problems I listed below

Add the following configuration to rules of.eslintrc.js

{
// JSX not allowed in files with extension '. TSX 'enables JSX syntax for TSX files
'react/jsx-filename-extension': [2, { extensions: ['.js'.'.jsx'.'.ts'.'.tsx']}],'React' must be in scope when using JSX
'react/react-in-jsx-scope': 'off'.// resolve 'React' was used before it was defined
'@typescript-eslint/no-use-before-define': ['error'].'no-use-before-define': 'off'.// Missing file extension "TSX" for 'XXX'
'import/extensions': [
  'error'.'ignorePackages',
  {
    ts: 'never'.tsx: 'never'],},// Disable the default export. D. ts
'import/prefer-default-export': 'off',},Copy the code

Yarn start 🎉 🎉 🎉 🎉 🎉

Vite

typescript

You don’t need a loader to install typescript

scss

No other loader is required to install sass

Eslint | prettier ditto for

vite

Install vite @ vitejs/plugin – react

Create vite. Config. ts in the root directory

The following

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
});
Copy the code

Write script to package.json

"dev": "vite",
"build": "tsc && vite build",
"serve": "vite preview",
Copy the code

Ditto the FAQ

Yarn Dev 🎉 🎉 🎉 🎉 🎉

Snowpack

snowpack

Other basic configurations are similar and will not be described here

Snowpack has its own ecology first install the following packages

  • snowpack

  • @snowpack/plugin-sass

  • @snowpack/plugin-react-refresh

  • @snowpack/plugin-typescript

Their names give you a rough idea of what they do

Snowpack has its own configuration file snowpack.config.mjs

Refer to official for detailed configuration

www.snowpack.dev/reference/c…

/ * *@type {import("snowpack").SnowpackUserConfig } * /
export default {
  mount: {
    // Static resource path
    public: { url: '/'.static: true },
    // Package the path
    src: { url: '/dist'}},// Configure some plug-ins
  plugins: [
    '@snowpack/plugin-sass'.'@snowpack/plugin-react-refresh'.'@snowpack/plugin-typescript',]};Copy the code

Yarn start 🎉 🎉 🎉 🎉 🎉

Add the script package. Json

"start": "snowpack dev",
"build": "snowpack build",
Copy the code

Git

Git commit information control is added here

We need to introduce Husky Lint-staged and commit-Lint

yarn add -D husky lint-staged @commitlint/config-conventional @commitlint/cli cz-conventional-changelog
Copy the code

Next we’ll add.lintStageDRC.json

{
  "*.{js,jsx,ts,tsx}": ["eslint --cache"]}Copy the code

Next add commitlint.config.js

module.exports = { extends: ['@commitlint/config-conventional']};Copy the code

Finally, run the following command

npm set-script prepare "husky install"
npm run prepare

npx husky add .husky/pre-commit "npx --no-install lint-staged"
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
Copy the code

After the execution, change the. Husky /commit-msg content as follows

#! /bin/sh . "$(dirname "$0")/\_/husky.sh" npx --no-install commitlint --edit "$1"Copy the code

Package. Add in json

"scripts": {
  "commit": "./node_modules/.bin/git-cz"
},
Copy the code

At this point, you can commit the commit as yarn COMMIT

You can also use git commit -m XXX

Throw an exception whenever your COMMIT is not canonical

🎉 🎉 🎉