create-react-app是由React官方提供,并推荐构建React单页应用程序的最佳方法,但是默认不支持less,需要手动修改配置文件,那么如何修改create-react-app配置?
1、安装loader
命令:npm install less-loader less
2,使用命令npm run eject或者yarn eject
(npm run eject表示拷贝一份配置文件,覆盖掉node-modules配置)
安装之后文件夹会多出config文件和script文件
修改weppack.config.js文件中,添加less配置
修改两处:
1.在module.rules节点中找到 css 文件的加载规则:
test: /\.css$/修改为test: /\.(css|less)$/;
2.在use数组最后新增一个对象元素{loader: require.resolve('less-loader')}
(上面是折叠后的,未折叠的代码部分如下:)
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
].filter(Boolean);
{loader: require.resolve('less-loader')}//*****************修改处
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
修改完成后:
需要重新启动项目,即可使用less样式
网友评论