Create-react-app+Antd+Less 在專案yarn eject 的情況下進行配置
阿新 • • 發佈:2018-12-05
一:建立一個react專案
npx create-react-app project
二:暴露所有內建的配置(注:我這裡用的是yarn)
yarn eject
注:如果yarn eject 報錯的解決的方法
git add .
git commit -m 'aa'
yarn eject
三:使用babel-plugin-import實現Antd按需載入,並修改package.json
yarn add babel-plugin-import --save-dev
package.json :
"babel": { "presets": [ "react-app" ], "plugins": [ [ "import", { "libraryName": "antd", "style": "css" } ] ] }
四:安裝less-loader 和 less
yarn add less-loader less --save-dev
五:修改config資料夾下的webpack.config.dev.js和webpack.config.prod.js檔案(都需要修改)
1.在oneOf中新增
oneOf: [ ... { test: /\.(css|less)$/, use: [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: { importLoaders: 1, }, }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, { loader: require.resolve('less-loader') // compiles Less to CSS } ], }, ]
2.查詢exclude
原本的 exclude: [/\.js$/, /\.html$/, /\.json$/],
修改為 exclude: [/\.html$/, /\.(js|jsx)$/, /\.(css|less)$/, /\.json$/, /\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
六:在App.js中運用
/* * @Author: Twinkle * @Date: 2018-11-07 11:34:48 * @Last Modified by: Twinkle * @Last Modified time: 2018-11-07 11:34:48 */ import React, { Component } from 'react'; import './App.less'; import { Button } from 'antd'; class App extends Component { render() { return ( <div> <p>按需載入antd</p> <Button>點選</Button> </div> ); } } export default App;
建立App.less
/*
* @Author: Twinkle
* @Date: 2018-11-07 11:35:57
* @Last Modified by: Twinkle
* @Last Modified time: 2018-11-07 11:35:57
*/
div{
color: aquamarine;
}
7: yarn start
完成