React 如何适用less
1.使用 create-react-app 创建的项目,默认情况下是看不到 webpack 相关的配置文件,我们需要给它暴露出来,使用下面命令即可:
npm run eject
2.添加less
npm install less less-loader --save-dev
3.修改webpack配置文件 (修改下面两段代码即可)
const cssRegex = /\.(css|less)$/; 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, }, { loader: require.resolve('less-loader'),// compiles Less to CSS 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); if (preProcessor) { loaders.push( { loader: require.resolve('resolve-url-loader'), options: { sourceMap: isEnvProduction && shouldUseSourceMap, }, }, { loader: require.resolve(preProcessor), options: { sourceMap: true, }, } ); } return loaders; };