記create-react-app 配置webpack

create-react-app 配置webpack

前言

最近一直用vue作技術棧,很久沒有用react了,因此直接用react開搞。javascript

create-react-app my-progress --typescript
複製代碼

一、修改webpack配置文件,須要安裝 react-app-rewired customize-cra

yarn add react-app-rewired customize-cra -D
複製代碼

二、修改package.json文件

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"
  },
複製代碼

三、在項目根目錄新建config-overrides.js

const { override } = require('customize-cra');
module.exports = {};
複製代碼

四、添加配置,跨域設置、增長less支持、px轉rem、ant-design-mobile按需加載、打包壓縮js和css

// 安裝less less-loader
yarn add less less-loader -D
// 安裝compression-webpack-plugin 壓縮js爲gzip
yarn add compression-webpack-plugin -D

const { override, overrideDevServer, addLessLoader, addPostcssPlugins, fixBabelImports } = require('customize-cra');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
// 打包配置
const addCustomize = () => config => {
  if (process.env.NODE_ENV === 'production') {
    // 關閉sourceMap
    config.devtool = false;
    // 配置打包後的文件位置
    config.output.path = __dirname + '../dist/demo/';
    config.output.publicPath = './demo';
    // 添加js打包gzip配置
    config.plugins.push(
      new CompressionWebpackPlugin({
        test: /\.js$|\.css$/,
        threshold: 1024,
      }),
    )
  }
  return config;
}
// 跨域配置
const devServerConfig = () => config => {
  return {
    ...config,
    // 服務開啓gzip
    compress: true,
    proxy: {
      '/api': {
        target: 'xxx',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api',
        },
      }
    }
  }
}
module.exports = {
  webpack: override(
    fixBabelImports('import', {
      libraryName: 'antd-mobile',
      style: 'css',
    }),
    addLessLoader(),
    addPostcssPlugins([require('postcss-pxtorem')({ rootValue: 75, propList: ['*'], minPixelValue: 2, selectorBlackList: ['am-'] })]),
    addCustomize(),
  ),
  devServer: overrideDevServer(
    devServerConfig()
  )
}
複製代碼

flex佈局在低版本手機不兼容

測試小朋友和我說在低版本ios8的系統樣式直接錯亂,這邊經過safari調試發現原來是flex沒有添加前綴致使。 直接修改package.json文件中的browserslistcss

"browserslist": {
    "defaults",
    "not ie < 11",
    "last 2 versions",
    "> 1%",
    "iOS 7",
    "last 3 iOS versions"
}
複製代碼

ok,完美。vue

參考

antd-mobile
customize-crajava

相關文章
相關標籤/搜索