第一次嘗試React+antd,發現果然不愧是傳說中的坑貨,一個又一個坑。必須要記錄。
react + antd,都是最新版本,使用npm和yarn各種add,build,start
1. 資源文件,圖片文件,路徑在build之后會不能用
我們希望的是http://xxxxxxx/AAA/img/XX.png
但build之后給出的是http://xxxxxxx/static/media/XX.png
解決方案:
node_modules -> react-scripts -> config -> paths.js 第46行
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');//改成'./'
return ensureSlash(servedUrl, true);
}
圖像的路徑對應也要改成 <img src={require('./../img/logo.png')} alt=""/>,非得添加一個 “./”
2. 自定義css會造成antd的css不起作用
這個超級坑,也完全出乎我的意料,也不知道到底是react還是webpack還是antd的鍋。都說react開發大坑無數,算是見識到了。
對付這個問題的中心思想是把自定義的css導入和antd的導入分開處理:
node_modules -> react-scripts -> config -> webpack.config.dev.js
這個是為dev環境設置:
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// @remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
// @remove-on-eject-end
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
//********** add ********/
plugins: [
[
"import",
{libraryName: "antd", style: 'css'}
]
]
//********** add ********/
},
這段我試過必須加,不加還不行。
然后
{
test: /\.css$/,
exclude:/src/,//********** add ********/
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', }), ], }, }, ], },
//********** add ********/
{
//CSS處理
test: /\.css$/,
loader: "style-loader!css-loader?modules", exclude: /node_modules/, },
//********** add ********/
都是網絡上尋找到然后試驗成功,是不是有冗余我也不知道,沒力氣仔細試了,這玩意搞了我好久,精疲力盡。
這樣dev環境下的css就顯示正常了
然而build的webpack.config.prod.js還需要重新設置一次:
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// @remove-on-eject-begin
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
// @remove-on-eject-end
compact: true,
//********** add ********/
plugins: [
[
"import", {libraryName: "antd", style: 'css'}
]
]
},
},
沒有進行css的分開處理,暫時沒發現問題,等待進一步探索。
build之后,沒有src和node_modules的區分,初步猜測也不需要再分開css,后續再看。
(待續)
