新建react项目全局引入antd样式踩坑
2019-06-03 本文已影响0人
曷心雨乙巳叩酊
新建了一个react项目,在使用react组件的时候,发现样式不生效。
按照官网的单独引入方式可以生效
import 'antd/dist/antd.css';
下面讲一讲全局引入的方法
首先安装babel-plugin-import
npm
npm install babel-plugin-import --save 或 cnpm install babel-plugin-import --save
yarn
yarn add babel-plugin-import
然后配置webpack.config.js
module.exports = {
entry: [
'./src/app.js'
],
output: {
path: __dirname + '/build',
filename: "bundle.js"
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: [
[
"import",
{libraryName: "antd", style: 'css'}
] //antd按需加载
],
presets: ['es2015', 'react', 'stage-2']
}
}, {//CSS处理
test: /\.(css||less)$/,
exclude: /node_modules/,
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')
}
],
},{//antd样式处理
test:/\.(css||less)$/,
exclude:/src/,
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')
}
]
}]
}
};
注意,如果按照
plugins: [
[
"import",
{libraryName: "antd", style: 'css'}
] //antd按需加载
]
引入,会发现antd的样式还是不生效,是因为要将系统的css和antd的css进行分开处理。