React 패밀리 버킷 환경 구축 코드 분석

php中世界最好的语言
풀어 주다: 2018-05-23 10:14:39
원래의
1485명이 탐색했습니다.

이번에는 React Family 버킷 환경 구축을 위한 코드 분석을 가져오겠습니다. React Family 버킷 환경 구축 시 주의사항은 무엇인가요?

환경 구축

1. 처음부터 webpack+react 개발 환경 구축

2.Typescript 도입

종속성 설치

npm i -S @types/react @types/react-dom
npm i -D typescript awesome-typescript-loader source-map-loader
로그인 후 복사

New tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react"
  },
  "include": [
    "./src/**/*"
  ]
}
로그인 후 복사

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
  },
};
로그인 후 복사
수정

3. less 도입 및 import less 모듈 지원

설치 종속성

npm i -D less less-loader
npm i -D typings-for-css-modules-loader
로그인 후 복사

팁: Typings-for-css-modules-loader

스타일 모듈화패키징 시import 또는 require를 통해 스타일을 도입할 수 있으며, 이는 상호 배타적 충돌입니다. .

//demo.less -> demo.less.d.ts
//.demo{color:red;} -> export const demo: string;
import * as styles from 'demo.less'
<DemoComponent className={styles.demo} />
로그인 후 복사

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
  },
};
로그인 후 복사

4.react-routerv4 도입

npm i -S react-router-dom
로그인 후 복사

기록 생성

import { createHashHistory } from 'history';
export default createHashHistory();
로그인 후 복사

사용

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')
);
로그인 후 복사

...ES7 구문 오류 보고

npm i -S babel-preset-stage-2
로그인 후 복사

.babelrc

{
 "presets": ["es2015", "react", "stage-2"],
}
로그인 후 복사

5.Introd uce mobx 상태 관리

npm i -S mobx mobx-react
로그인 후 복사

데코레이터 구문 사용

Modify tsconfig.json

"compilerOptions": {
  "target":"es2017", //fix mobx.d.ts error
  "experimentalDecorators": true,
  "allowJs": true
}
로그인 후 복사
npm i -D babel-plugin-transform-decorators-legacy
로그인 후 복사

Modify .babelrc

{
 "presets": ["es2015", "react", "stage-2"],
 "plugins": ["transform-decorators-legacy"]
}
로그인 후 복사

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 다른 관련 기사를 주목하세요. PHP 중국어 웹사이트에서!

추천 자료:

JS가 로컬 카메라 기능을 호출하는 단계에 대한 자세한 설명

JS가 객체 속성별로 정렬되는 json 객체 배열을 구현하는 단계에 대한 자세한 설명

위 내용은 React 패밀리 버킷 환경 구축 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!