Home Web Front-end JS Tutorial React family bucket environment construction code analysis

React family bucket environment construction code analysis

May 23, 2018 am 10:14 AM
react code build

This time I will bring you the code analysis for building the React family bucket environment. What are the precautions for building the React family bucket environment? The following is a practical case, let’s take a look.

Environment setup

1. Build a webpack react development environment from scratch

2.Introduce Typescript

Installation dependencies

1

2

npm i -S @types/react @types/react-dom

npm i -D typescript awesome-typescript-loader source-map-loader

Copy after login

New tsconfig.json

1

2

3

4

5

6

7

8

9

10

11

12

13

{

  "compilerOptions": {

    "outDir""./dist/",

    "sourceMap": true,

    "noImplicitAny": true,

    "module""commonjs",

    "target""es5",

    "jsx""react"

  },

  "include": [

    "./src/**/*"

  ]

}

Copy after login

Modify webpack.config.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

// webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const webpack = require('webpack');

module.exports = {

  entry: {

    index:'./src/index.js',

  },

  output: {

    filename: 'bundle.js',

    path: path.resolve(dirname, 'dist')

  },

  devtool: "source-map",

  // Add '.ts' and '.tsx' as resolvable extensions.

  resolve: {

    extensions: ['.ts''.tsx''.js''.jsx']

  },

  module: {

    rules: [

      {

        test: /\.css$/,

        use: ['style-loader''css-loader']

      },

      {

        test: /\.(png|svg|jpg|gif)$/,

        use: ['url-loader']

      },

      {

        test: /\.(woff|woff2|eot|ttf|otf)$/,

        use: ['url-loader']

      },

      {

        test: /\.(js|jsx)$/,

        exclude: /node_modules/,

        use: {

          loader: 'babel-loader'

        }

      },

      // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.

      {

        test: /\.tsx?$/,

        loader: "awesome-typescript-loader"

      },

    ]

  },

  plugins: [

    new HtmlWebpackPlugin({

      title: 'production',

      template: './index.html'

    }),

    new webpack.NamedModulesPlugin(),

    new webpack.HotModuleReplacementPlugin()

  ],

  devServer: {

    contentBase: './dist',

    hot: true

  },

};

Copy after login

3. Introduce less and support import less modules

Install dependencies

1

2

npm i -D less less-loader

npm i -D typings-for-css-modules-loader

Copy after login

tips:typings-for-css-modules-loader

Modularize the styles when packaging, we can introduce styles through import or require, and interact with each other Do not conflict.

1

2

3

4

//demo.less -> demo.less.d.ts

//.demo{color:red;} -> export const demo: string;

import * as styles from 'demo.less'

<DemoComponent className={styles.demo} />

Copy after login

Modify webpack.config.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

// webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const webpack = require('webpack');

module.exports = {

  entry: {

    index:'./src/index.js',

  },

  output: {

    filename: 'bundle.js',

    path: path.resolve(dirname, 'dist')

  },

  devtool: "source-map",

  //add .less

  resolve: {

    extensions: ['.ts''.tsx''.js''.jsx''.less''.css']

  },

  module: {

    rules: [

      {

        test: /\.css$/,

        use: ['style-loader''css-loader']

      },

      //import less modules,name:demodemo_hash

      {

        test: /\.less/,

        use: [

          'style-loader',

          'typings-for-css-modules-loader?modules&importLoaders=1&localIdentName=[name][local]_[hash:base64:5]&namedExport&camelCase&less!less-loader'

        ]

      },

      {

        test: /\.(png|svg|jpg|gif)$/,

        use: ['url-loader']

      },

      {

        test: /\.(woff|woff2|eot|ttf|otf)$/,

        use: ['url-loader']

      },

      {

        test: /\.(js|jsx)$/,

        exclude: /node_modules/,

        use: {

          loader: 'babel-loader'

        }

      },

      {

        test: /\.tsx?$/,

        loader: "awesome-typescript-loader"

      },

    ]

  },

  plugins: [

    new HtmlWebpackPlugin({

      title: 'production',

      template: './index.html'

    }),

    new webpack.NamedModulesPlugin(),

    new webpack.HotModuleReplacementPlugin()

  ],

  devServer: {

    contentBase: './dist',

    hot: true

  },

};

Copy after login

4.Introduce react-routerv4

1

npm i -S react-router-dom

Copy after login

Create history

1

2

import { createHashHistory } from 'history';

export default createHashHistory();

Copy after login

Use

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import React from 'react';

import ReactDom from 'react-dom';

import * as styles from "./index.less";

import history from './helpers/history';

import {Router, Route, Switch, Redirect, Link} from 'react-router-dom';

import Hello from "./router/Hello";

import TodoList from "./router/TodoList";

const PrivateRoute = ({ component: Component , ...rest}) => {

  return (

    <Route {...rest} render={props => (

      <Component {...props}/>

    )}/>

  );

}

ReactDom.render(

  <Router history={history} >

    <p className={styles.wrap}>

      <ul>

        <li><Link to="/">Homes</Link></li>

        <li><Link to="/todo">TodoList</Link></li>

      </ul>

      <Switch>

        <Route exact path="/" component={Hello}/>

        {/*<Route path="/demo" component={Demo}/>*/}

        <PrivateRoute path="/todo" component={TodoList} />

      </Switch>

    </p>

  </Router>,

  document.getElementById('root')

);

Copy after login

...ES7 syntax error

1

npm i -S babel-preset-stage-2

Copy after login

Modify .babelrc

1

2

3

{

 "presets": ["es2015""react""stage-2"],

}

Copy after login

5. Introduce mobx state management

1

npm i -S mobx mobx-react

Copy after login

Use decorator syntax

Modify tsconfig.json

1

2

3

4

5

"compilerOptions": {

  "target":"es2017"//fix mobx.d.ts error

  "experimentalDecorators": true,

  "allowJs": true

}

Copy after login

1

npm i -D babel-plugin-transform-decorators-legacy

Copy after login

Modify .babelrc

1

2

3

4

{

 "presets": ["es2015""react""stage-2"],

 "plugins": ["transform-decorators-legacy"]

}

Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for JS to call the local camera function

JS steps to implement json object array sorting by object properties Detailed explanation

The above is the detailed content of React family bucket environment construction code analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
How to use Copilot to generate code How to use Copilot to generate code Mar 23, 2024 am 10:41 AM

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for &quot;PowerPlatformTool&quot; and click the Install button

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! The Mistral open source code model takes the throne! Codestral is crazy about training in over 80 languages, and domestic Tongyi developers are asking to participate! Jun 08, 2024 pm 09:55 PM

Produced by 51CTO technology stack (WeChat ID: blog51cto) Mistral released its first code model Codestral-22B! What’s crazy about this model is not only that it’s trained on over 80 programming languages, including Swift, etc. that many code models ignore. Their speeds are not exactly the same. It is required to write a "publish/subscribe" system using Go language. The GPT-4o here is being output, and Codestral is handing in the paper so fast that it’s hard to see! Since the model has just been launched, it has not yet been publicly tested. But according to the person in charge of Mistral, Codestral is currently the best-performing open source code model. Friends who are interested in the picture can move to: - Hug the face: https

Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Apr 17, 2024 pm 02:28 PM

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

See all articles