美文网首页
新版create-react-app eject 配置及代理(未

新版create-react-app eject 配置及代理(未

作者: 芒果加奶 | 来源:发表于2019-02-15 17:11 被阅读0次

一、配置less

yarn add less less-loader 
// webpack.config.js 新版已配置SaaS
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

         {
            test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
                },
                'less-loader'
              ),
              sideEffects: true
            },
            {
              test: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
                  modules: true,
                  getLocalIdent: getCSSModuleLocalIdent
                },
                'less-loader'
              )
            },

二、安装antd,同时修改默认主题

yarn add antd babel-plugin-import 

引用antd

import {Button} from 'antd'

package.json中修改,也可以在webpack.config.js中更改,不过需要修改dev和prod两个环境。

"babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "libraryDirectory": "es",
          "style": "css"
        }
      ]
    ]
  }

修改默认主题

// 首先 babel插件中 style改成true
"babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "libraryDirectory": "es",
          "style": true // // `style: true` 会加载 less 文件
        }
      ]
    ]
  }
// 然后在webpack中修改getStyleLoaders方法,新版less loader抽成公共函数了
const getStyleLoaders = (cssOptions, preProcessor) => {
    const loaders = [
      isEnvDevelopment && require.resolve('style-loader'),
      isEnvProduction && {
        loader: MiniCssExtractPlugin.loader,
        options: Object.assign({}, shouldUseRelativeAssetPaths ? { publicPath: '../../' } : undefined)
      },
      {
        loader: require.resolve('css-loader'),
        options: cssOptions
      },
      {
        // Options for PostCSS as we reference these options twice
        // Adds vendor prefixing based on your specified browser support in
        // package.json
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebook/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            require('postcss-preset-env')({
              autoprefixer: {
                flexbox: 'no-2009'
              },
              stage: 3
            })
          ],
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
        }
      }
    ].filter(Boolean);
    // 修改这里
    if (preProcessor) {
      // loaders.push({
      //   loader: require.resolve(preProcessor),
      //   options: {
      //     sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
      //   }
      // });
      let loader = require.resolve(preProcessor);
      if (preProcessor === 'less-loader') {
        loader = {
          loader,
          options: {
            modifyVars: {
              'primary-color': 'red'
            },
            javascriptEnabled: true
          }
        };
      }
      loaders.push(loader);
    }
    return loaders;
  };

没有生效? antd官网提示

注意样式必须加载 less 格式,一个常见的问题就是引入了多份样式,less 的样式被 css 的样式覆盖了。

  • 如果你在使用 babel-plugin-importstyle 配置来引入样式,需要将配置值从 'css' 改为 true,这样会引入 less 文件。

  • 如果你是通过 'antd/dist/antd.css' 引入样式的,改为 antd/dist/antd.less

三、react -hot-loader

修改的部分自动刷新,和自动刷新网页不同的是,hot-loader并不会刷新网页,仅仅是替换修改的部分。
配置react-hot-loader

yarn add react-hot-loader -s

修改webpack.config.js

{
              test: /\.(js|mjs|jsx|ts|tsx)$/,
              include: paths.appSrc,
              loader: require.resolve('babel-loader'),
              options: {
                customize: require.resolve('babel-preset-react-app/webpack-overrides'),

                plugins: [
                  [
                    require.resolve('babel-plugin-named-asset-import'),
                    {
                      loaderMap: {
                        svg: {
                          ReactComponent: '@svgr/webpack?-svgo![path]'
                        }
                      }
                    },
                    "react-hot-loader/babel"  // plugin中加上react-hot-loader
                  ]
                ],
                cacheDirectory: true,
                cacheCompression: isEnvProduction,
                compact: isEnvProduction
              }
            },

在App.js中配置使用

import { hot } from 'react-hot-loader';
export default hot(module)(App);

重启后可以看到修改部分已经刷新而浏览器网页没有刷新。

四、配置redux

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { applyMiddleware, compose, createStore } from 'redux';
import { createBrowserHistory } from 'history';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
import { Provider } from 'react-redux';
import { LocaleProvider } from 'antd';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import { AppContainer } from 'react-hot-loader';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './reducers/saga';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

export const history = createBrowserHistory(); // 路由

let sagaMiddleware = createSagaMiddleware(); //创建saga中间件
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  createRootReducer(history), // root reducer with router state
  composeEnhancer(
    applyMiddleware(
      sagaMiddleware,
      routerMiddleware(history) // for dispatching history actions
      // ... other middlewares ...
    )
  )
);

sagaMiddleware.run(rootSaga);

// AppContainer(hot-loader)=》LocaleProvider (antd国际化)=》Provider (react-redux顶级组件放入store=》App 页面最高级组件负责路由)
const render = () => {
  ReactDOM.render(
    <AppContainer> 
      <LocaleProvider locale={zhCN}>
        <Provider store={store}>
          <App history={history} />
        </Provider>
      </LocaleProvider>
    </AppContainer>,
    document.getElementById('root')
  );
};
render();
serviceWorker.unregister();

// App.js
import React from 'react';
import { hot } from 'react-hot-loader';
import { ConnectedRouter } from 'connected-react-router';
import routes from './routes';
import PropTypes from 'prop-types';

// 关联路由
const App = ({ history }) => {
  return <ConnectedRouter history={history}>{routes}</ConnectedRouter>;
};

App.propTypes = {
  history: PropTypes.object
};

export default hot(module)(App);

// router.js
import React from 'react';
import { Route, Switch } from 'react-router';

const Home = props => (
  <div>
    <h2>haha </h2>
  </div>
);

const routes = (
  <Switch>
    <Route exact path='/' component={Home} />
  </Switch>
);
export default routes;
// reducer.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

const createRootReducer = history =>
  combineReducers({
    router: connectRouter(history)
  });

export default createRootReducer;
// saga.js
import { all } from "redux-saga/effects";
import { watchFetchCate } from "./global";

export default function* rootSaga() {
  yield all([watchFetchCate()]);
}

五、配置代理

新版本cra脚手架在package.json中使用proxy只能用字符串了。官网给了新的使用方式,在src下新建文件setupProxy.js加下面代码,无需单独应用,webpack会自动引入文件。
一个大坑:因为我用typescript了,文件名结尾.ts导致文件不生效!!!切记.js文件结尾

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/house', { target: 'https://evaluatepre.jd.com' }));
  app.use(proxy('/vehicle', { target: 'https://evaluatepre.jd.com' }));
  app.use(
    proxy("/user", {
      target: "https://test.com",
      changeOrigin: true
    })
  );
  
};

相关文章

网友评论

      本文标题:新版create-react-app eject 配置及代理(未

      本文链接:https://www.haomeiwen.com/subject/jvnpeqtx.html