1. Introduction

Recently a sudden an idea, want to try to build a React project template from scratch, to making, then write the scaffold command pull templates and write a script command to quickly generate a business module, and then use this template together before a component library, compile pack to run a series of operation, and another thing, Using the project based on the project template and component library, the entire process of automated construction and automated deployment will be documented in serial articles for later traceability.

2. Initialize the project

Create a new project file and run the -y command. The default option is yes. This will generate a package.json file

npm init -y
Copy the code

3. Initialize typeScript configuration

The tsconfig.json file will be generated after the command is executed, and there will be configuration and description of all attributes in the file, which can be used in combination with your own requirements. Because tsconfig.json is too long, only some of my configuration items are left

yarn add typescript -g
tsc init
Copy the code
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    "target": "ES2016"./* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs"./* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "jsx": "react"./* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    /* Strict Type-Checking Options */
    "strict": true./* Enable all strict type-checking options. */
    "esModuleInterop": true./* Enables emit interoperability between CommonJS and ES Modules via creation of /* Advanced Options */
    "skipLibCheck": true./* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */}}Copy the code

4. Configuration react

4.1. Install dependencies

yarn add react react-dom react-router-dom
yarn add @types/react @types/react-dom @types/react-router-dom --dev
Copy the code

4.2. Create an HTML template

Create new index. HTML in the public directory

<! --public/index.html-->
<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="favicon" />
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
Copy the code

4.3. Create project entry file

Create app. TSX and index.tsx in the SRC directory

// App.tsx
import React from 'react';

const App = () = > {
  return <div>buildDemo</div>;
};

export default App;

// index.tsx
import App from './App';
import ReactDom from 'react-dom';
import React from 'react';

ReactDom.render(<App />.document.querySelector('#root'));
Copy the code

5. Configuration webpack

5.1. Installing webPack dependencies (WebPack version 5.x)

yarn add webpack webpack-cli webpack-merge html-webpack-plugin@next clean-webpack-plugin --dev
Copy the code

5.2. Description of dependency packages

html-webpack-plugin@next wepack 5 need to install 5.x version of html-webpack-plugin official website requirements, specific start will be explained

Clean-webpack-plugin Cleans up the plug-ins for the packaged directory

5.3. Create a WebPack configuration

Create a config file to store the webpack configuration file:

  • webpack.config.base.jsWebpack basic configuration
  • webpack.config.dev.jsWebpack development environment configuration
  • webpack.config.prod.jsWebpack production environment configuration
// webpack.config.base.js
// Type will be prompted when configured
/ * * *@type {import('webpack').Configuration}* /

module.exports = {
	entry: path.resolve(__dirname, '.. /src/index.tsx'),
	output: {
		filename: '[name].[hash].js'.path: path.resolve(__dirname, '.. /dist'),},resolve: {
		extensions: ['.ts'.'.tsx'.'.js'.'.jsx'],},plugins: [
		new HtmlWebpackPlugin({
			filename: 'index.html'.template: path.resolve(__dirname, '.. /publich/index.html'),
			favicon: path.resolve(__dirname, '.. /publich/favicon.ico'),
			hash: true,}).new CleanWebpackPlugin({
			dry: false.cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, 'dist')]}),]};Copy the code
// webpack.config.dev.js
/ * * *@type {import('webpack').WebpackOptionsNormalized}* /

const devConfig = {
	mode: 'development'};module.exports = webpackMerge.merge(baseConfig, devConfig);
Copy the code
// webpack.config.prod.js
/ * * *@type {import('webpack').Configuration}* /

const prodConfig = {
	mode: 'production'};module.exports = webpackMerge(baseConfig, prodConfig);
Copy the code

6. The configuration of Babel

6.1. Install dependencies (Babel version 7.x)

yarn add babel-loader babel-plugin-import @babel/cli @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript --dev
Copy the code

6.2. Description of dependency packages

Babel-loader is a file preprocessor, which is used by webpack to load static files

Babel-plugin-import can be loaded on demand for antD, ANTD-Mobile, Lodash, etc

@babel/cli Built-in CLI command line tool

@babel/core calls Babel’s API for transcoding and uses this module

@babel/preset-env is a flexible preset that allows you to use the latest JavaScript without having to manage syntactic conversions or browser polyfills required by the target environment

@ Babel/preset – react the react preset

@ Babel/preset – typescript typescript preset

6.3. Create the babel.config.js file

// Type will be prompted when written
/ * * *@type {import('@babel/core').TransformOptions}* /
module.exports = {
	presets: [['@babel/env',
			{
				useBuiltIns: 'usage'.corejs: 3],},'@babel/preset-react'.'@babel/preset-typescript',]};Copy the code

Add module configuration to webpack.config.base.js

/ * * *@type {import('webpack').Configuration}* /

module.exports = {
	...
	module: {
		rules: [{test: /\.(js|ts)x? $/,
				exclude: /(node_modules)/,
				use: {
					loader: 'babel-loader',},},],},};Copy the code

7. Configure the development server

yarn add webpack-dev-server --dev
Copy the code

Webpack.config.dev.js adds the following configuration

/ * * *@type {import('webpack-dev-server').Configuration}* /

const devServer = {
	port: 3000.host: 'localhost'.contentBase: path.join(__dirname, '.. /publich'),
	watchContentBase: true.publicPath: '/'.compress: true.historyApiFallback: true.hot: true.clientLogLevel: 'error'.// open: true,
	watchOptions: {
		ignored: /node_modules/,}};/ * * *@type {import('webpack').WebpackOptionsNormalized}* /

const devConfig = {
	mode: 'development'.devServer: devServer,
};

module.exports = webpackMerge.merge(baseConfig, devConfig);
Copy the code

Add startup commands to package.json

"scripts": {
	"start": "webpack serve --config ./config/webpack.config.dev.js"
},
Copy the code

8. To start the

8.1.Error: Cannot find module ‘webpack-cli/bin/config-yargs’

During the startup of webpack-dev-server, if the webpack-CLI version is 4, this error is reported

There are two solutions:

  1. Modify command"start": "webpack serve --config ./config/webpack.config.dev.js"
  2. To reducewebpack-cliVersion to 3

Start again to throw this problem, check becausewebpack.config.base.jsIn theResolve the extensionsNot associated.js,.jsx

8.2.Error: Uglify SyntaxError: Unexpected Token: punc ())

When usingUglifyJsThis error occurs when compression occurs, refer to the relevant information isES6Syntax compression problem

Solutions: * * move UglifyJs to webpack. Optimization. The minimizer

Reference: stackoverflow.com/questions/4…

8.3.Error: Failed to decode param ‘/%PUBLIC_URL%/favicon.ico

The reason for this problem is that the dependencies I downloaded myself didn’t pay attention to the version

Solution:

  1. Refer tohtml-webpack-pluginiswebpack5Use this version of the plugin"HTML - webpack - plugin" : "^ 5.0.0 - alpha. 14",
  2. Another solution is to roll backwebpackGo to 4 and then useInterpolateHtmlPluginreplace/%PUBLIC_URL%/

9. Reference materials

Juejin. Cn/post / 684490…

The first record to write an article, writing limited, many inclusive, ヾ(´ 漢 ‘) Blue Thank you