问题描述:
在react中使用antd 组件后页面没有样式。
问题原因:
因为组件的css 没有按需加载
在 webpack 配置文件中,加入此行代码 重启后即可;
整体webpack配置如下:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
function resolve(relatedPath) {
return path.join(__dirname, relatedPath)
}
module.exports = {
mode: 'development',
entry: {
/*react-hot-loader/patch,为了保留住state数据,没有使用webpack内置的hot热替换*/
app: ['babel-polyfill', 'react-hot-loader/patch', path.join(__dirname, 'src/app.js')]
}, /*入口程序*/
output: {
path: path.join(__dirname, './dist'), /*输出文件目录*/
publicPath: "/",
filename: 'bundle.js' /*打包文件名称*/
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
plugins: [
["import", {libraryName: "antd-mobile", style: "css"}] //按需加载
]
},
},
{
test: /\.(png|jpg|svg|gif)$/,
loader: 'file-loader'
},
{
test: /\.(sa|sc|c)ss$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader',
],
}
],
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, './dist'),
historyApiFallback: true,
host: "0.0.0.0",
port: "3000",
hot: true,
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}),
new webpack.NamedModulesPlugin(), /*查看修补的依赖*/
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: resolve('src/index.html'),
}),
],
resolve: {
alias: {
containers: path.join(__dirname, 'src/containers'),
components: path.join(__dirname, 'src/components'),
utils: path.join(__dirname, 'src/utils'),
charts: path.join(__dirname, 'src/components/Charts'),
public: path.join(__dirname, 'src/public'),
}
}
}