Home > Web Front-end > JS Tutorial > body text

How to build a React family bucket environment

php中世界最好的语言
Release: 2018-05-28 15:38:59
Original
2043 people have browsed it

This time I will show you how to build a React family bucket environment and what are the precautions for building a 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

npm i -S @types/react @types/react-dom
npm i -D typescript awesome-typescript-loader source-map-loader
Copy after login

New tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react"
  },
  "include": [
    "./src/**/*"
  ]
}
Copy after login

Modify webpack.config.js

// 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

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.

//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

// 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

npm i -S react-router-dom
Copy after login

Create history

import { createHashHistory } from 'history';
export default createHashHistory();
Copy after login

Use

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

npm i -S babel-preset-stage-2
Copy after login

Modify .babelrc

{
 "presets": ["es2015", "react", "stage-2"],
}
Copy after login

5. Introduce mobx state management

npm i -S mobx mobx-react
Copy after login

Use decorator syntax

Modify tsconfig.json

"compilerOptions": {
  "target":"es2017", //fix mobx.d.ts error
  "experimentalDecorators": true,
  "allowJs": true
}
Copy after login
npm i -D babel-plugin-transform-decorators-legacy
Copy after login

Modify .babelrc

{
 "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:

How to use JS to implement json object array sorting by object properties

How to operate vue.js 3DES encryption

The above is the detailed content of How to build a React family bucket environment. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template