第一次尝试React+antd,发现果真不愧是传说中的坑货,一个又一个坑。必需要记录。css
react + antd,都是最新版本,使用npm和yarn各类add,build,startjava
1. 资源文件,图片文件,路径在build以后会不能用node
咱们但愿的是http://xxxxxxx/AAA/img/XX.pngreact
但build以后给出的是http://xxxxxxx/static/media/XX.pngwebpack
解决方案:git
node_modules -> react-scripts -> config -> paths.js 第46行github
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=""/>,非得添加一个 “./”web
2. 自定义css会形成antd的css不起做用npm
这个超级坑,也彻底出乎个人意料,也不知道究竟是react仍是webpack仍是antd的锅。都说react开发大坑无数,算是见识到了。babel
对付这个问题的中心思想是把自定义的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,后续再看。
(待续)