您好,欢迎访问一九零五行业门户网

react antd-mobile项目中如何实现 css 与 less 局部作用域化的功能

这篇文章给大家介绍的内容是关于react antd-mobile项目中如何实现 css 与 less 局部作用域化的功能,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、前言最近搭建的 react 项目想引入 less ,并实现样式局部作用域化,但是在网上找了很多方法试过了都不行,最后打到解决方法,在此记下这惨痛的历程。
2、create-react-appcreate-react-app 是业界最优秀的 react 相关应用开发工具之一,本文档就是以此工具来使用 antd-mobile 组件。
安装和初始化#$ npm install -g create-react-app# 注意:工具会自动初始化一个脚手架并安装 react 项目的各种必要依赖,如果在过程中出现网络问题,请尝试配置代理或使用其他 npm registry。$ create-react-app my-app$ cd my-app$ npm start
打开 http://localhost:3000/ 访问你的应用。
3、修改 css 配置下面是修改文件 webpack.config.js。
module.exports = {   entry: __dirname + '/index.js',   output: {     publicpath: '/',     filename: './bundle.js'   },   module: {     loaders: [       {         test: /\.jsx?$/,         exclude: /node_modules/,         loader: 'babel',         query: {           presets: ['es2015', 'stage-0', 'react']         }       },       {         test: /\.css$/,         loader: style-loader!css-loader?modules       },     ]   } };
上面代码中,关键的一行是style-loader!css-loader?modules,它在css-loader后面加了一个查询参数modules,表示打开 css modules 功能。
4、 配置 less首先安装 less 和 less-loader
npm i --save-dev less less-loader
然后在 webpack.config.dev 中配置 less :
//这里我开启自己编写的less文件的css modules功能 除了node_modules库中的less,                    //也就是可以过滤掉antd库中的样式                    {                        test: /\.less$/,                        exclude: [/node_modules/],                        use: [                            require.resolve('style-loader'),                            {                                loader: require.resolve('css-loader'),                                options: {                                    modules: true,                                    localindexname: [name]__[local]___[hash:base64:5]                                },                            },                            {                                loader: require.resolve('less-loader'), // compiles less to css                            },                        ],                    },
5、完整配置送上完整的 webpack.config.dev  配置:
'use strict';const autoprefixer = require('autoprefixer');const path = require('path');const webpack = require('webpack');const htmlwebpackplugin = require('html-webpack-plugin');const casesensitivepathsplugin = require('case-sensitive-paths-webpack-plugin');const interpolatehtmlplugin = require('react-dev-utils/interpolatehtmlplugin');const watchmissingnodemodulesplugin = require('react-dev-utils/watchmissingnodemodulesplugin');const eslintformatter = require('react-dev-utils/eslintformatter');const modulescopeplugin = require('react-dev-utils/modulescopeplugin');const getclientenvironment = require('./env');const paths = require('./paths');// webpack uses `publicpath` to determine where the app is being served from.// in development, we always serve from the root. this makes config easier.const publicpath = '/';// `publicurl` is just like `publicpath`, but we will provide it to our app// as %public_url% in `index.html` and `process.env.public_url` in javascript.// omit trailing slash as %public_path%/xyz looks better than %public_path%xyz.const publicurl = '';// get environment variables to inject into our app.const env = getclientenvironment(publicurl);// this is the development configuration.// it is focused on developer experience and fast rebuilds.// the production configuration is different and lives in a separate file.module.exports = {    // you may want 'eval' instead if you prefer to see the compiled output in devtools.    // see the discussion in https://github.com/facebookincubator/create-react-app/issues/343.    devtool: 'cheap-module-source-map',    // these are the entry points to our application.    // this means they will be the root imports that are included in js bundle.    // the first two entry points enable hot css and auto-refreshes for js.    entry: [        // we ship a few polyfills by default:        require.resolve('./polyfills'),        // include an alternative client for webpackdevserver. a client's job is to        // connect to webpackdevserver by a socket and get notified about changes.        // when you save a file, the client will either apply hot updates (in case        // of css changes), or refresh the page (in case of js changes). when you        // make a syntax error, this client will display a syntax error overlay.        // note: instead of the default webpackdevserver client, we use a custom one        // to bring better experience for create react app users. you can replace        // the line below with these two lines if you prefer the stock client:        // require.resolve('webpack-dev-server/client') + '?/',        // require.resolve('webpack/hot/dev-server'),        require.resolve('react-dev-utils/webpackhotdevclient'),        // finally, this is your app's code:        paths.appindexjs,        // we include the app code last so that if there is a runtime error during        // initialization, it doesn't blow up the webpackdevserver client, and        // changing js code would still trigger a refresh.    ],    output: {        // add /* filename */ comments to generated require()s in the output.        pathinfo: true,        // this does not produce a real file. it's just the virtual path that is        // served by webpackdevserver in development. this is the js bundle        // containing code from all our entry points, and the webpack runtime.        filename: 'static/js/bundle.js',        // there are also additional js chunk files if you use code splitting.        chunkfilename: 'static/js/[name].chunk.js',        // this is the url that app is served from. we use / in development.        publicpath: publicpath,        // point sourcemap entries to original disk location (format as url on windows)        devtoolmodulefilenametemplate: info =>            path.resolve(info.absoluteresourcepath).replace(/\\/g, '/'),    },    resolve: {        // this allows you to set a fallback for where webpack should look for modules.        // we placed these paths second because we want `node_modules` to win        // if there are any conflicts. this matches node resolution mechanism.        // https://github.com/facebookincubator/create-react-app/issues/253        modules: ['node_modules', paths.appnodemodules].concat(            // it is guaranteed to exist because we tweak it in `env.js`            process.env.node_path.split(path.delimiter).filter(boolean)        ),        // these are the reasonable defaults supported by the node ecosystem.        // we also include jsx as a common component filename extension to support        // some tools, although we do not recommend using it, see:        // https://github.com/facebookincubator/create-react-app/issues/290        // `web` extension prefixes have been added for better support        // for react native web.        extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],        alias: {            // support react native web            // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/            'react-native': 'react-native-web',        },        plugins: [            // prevents users from importing files from outside of src/ (or node_modules/).            // this often causes confusion because we only process files within src/ with babel.            // to fix this, we prevent you from importing files out of src/ -- if you'd like to,            // please link the files into your node_modules/ and let module-resolution kick in.            // make sure your source files are compiled, as they will not be processed in any way.            new modulescopeplugin(paths.appsrc, [paths.apppackagejson]),        ],    },    module: {        strictexportpresence: true,        rules: [            // todo: disable require.ensure as it's not a standard language feature.            // we are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.            // { parser: { requireensure: false } },            // first, run the linter.            // it's important to do this before babel processes the js.            {                test: /\.(js|jsx|mjs)$/,                enforce: 'pre',                use: [{                    options: {                        formatter: eslintformatter,                        eslintpath: require.resolve('eslint'),                    },                    loader: require.resolve('eslint-loader'),                }, ],                include: paths.appsrc,            },            {                // oneof will traverse all following loaders until one will                // match the requirements. when no loader matches it will fall                // back to the file loader at the end of the loader list.                oneof: [                    // url loader works like file loader except that it embeds assets                    // smaller than specified limit in bytes as data urls to avoid requests.                    // a missing `test` is equivalent to a match.                    {                        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],                        loader: require.resolve('url-loader'),                        options: {                            limit: 10000,                            name: 'static/media/[name].[hash:8].[ext]',                        },                    },                    // process js with babel.                    {                        test: /\.(js|jsx|mjs)$/,                        include: paths.appsrc,                        loader: require.resolve('babel-loader'),                        options: {                            // 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,                        },                    },                    {                        test: /\.css$/,                        loader: style-loader!css-loader?modules                    },                    //@lynn 这里我开启自己编写的less文件的css modules功能 除了node_modules库中的less,                    //也就是可以过滤掉antd库中的样式                    {                        test: /\.less$/,                        exclude: [/node_modules/],                        use: [                            require.resolve('style-loader'),                            {                                loader: require.resolve('css-loader'),                                options: {                                    modules: true,                                    localindexname:[name]__[local]___[hash:base64:5]                                },                            },                            {                                loader: require.resolve('less-loader'), // compiles less to css                            },                        ],                    },                    // file loader makes sure those assets get served by webpackdevserver.                    // when you `import` an asset, you get its (virtual) filename.                    // in production, they would get copied to the `build` folder.                    // this loader doesn't use a test so it will catch all modules                    // that fall through the other loaders.                    {                        // exclude `js` files to keep css loader working as it injects                        // its runtime that would otherwise processed through file loader.                        // also exclude `html` and `json` extensions so they get processed                        // by webpacks internal loaders.                        exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],                        loader: require.resolve('file-loader'),                        options: {                            name: 'static/media/[name].[hash:8].[ext]',                        },                    },                ],            },            // ** stop ** are you adding a new loader?            // make sure to add the new loader(s) before the file loader.        ],    },    plugins: [        // extractless,        // makes some environment variables available in index.html.        // the public url is available as %public_url% in index.html, e.g.:        // <link rel="shortcut icon" href="%public_url%/favicon.ico">        // in development, this will be an empty string.        new interpolatehtmlplugin(env.raw),        // generates an `index.html` file with the <script> injected.        new htmlwebpackplugin({            inject: true,            template: paths.apphtml,        }),        // add module names to factory functions so they appear in browser profiler.        new webpack.namedmodulesplugin(),        // makes some environment variables available to the js code, for example:        // if (process.env.node_env === 'development') { ... }. see `./env.js`.        new webpack.defineplugin(env.stringified),        // this is necessary to emit hot updates (currently css only):        new webpack.hotmodulereplacementplugin(),        // watcher doesn't work well if you mistype casing in a path so we use        // a plugin that prints an error when you attempt to do this.        // see https://github.com/facebookincubator/create-react-app/issues/240        new casesensitivepathsplugin(),        // if you require a missing module and then `npm install` it, you still have        // to restart the development server for webpack to discover it. this plugin        // makes the discovery automatic so you don't have to restart.        // see https://github.com/facebookincubator/create-react-app/issues/186        new watchmissingnodemodulesplugin(paths.appnodemodules),        // moment.js is an extremely popular library that bundles large locale files        // by default due to how webpack interprets its code. this is a practical        // solution that requires the user to opt into importing specific locales.        // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack        // you can remove this if you don't use moment.js:        new webpack.ignoreplugin(/^\.\/locale$/, /moment$/),    ],    // some libraries import node modules but don't use them in the browser.    // tell webpack to provide empty mocks for them so importing them works.    node: {        dgram: 'empty',        fs: 'empty',        net: 'empty',        tls: 'empty',        child_process: 'empty',    },    // turn off performance hints during development because we don't do any    // splitting or minification in interest of speed. these warnings become    // cumbersome.    performance: {        hints: false,    },};
webpack.config.prod 中的配置也同理,把 css 与 less 的配置覆盖到 webpack.config.prod 中相应的位置即可
相关文章推荐:
使用formdata()将ajax文件上传的代码
js简单实现防抖 - debounce和节流 - throttle
以上就是react antd-mobile项目中如何实现 css 与 less 局部作用域化的功能的详细内容。
其它类似信息

推荐信息