background

When developing the React project, we often write style in CSS, LESS, SCSS, after configuration processing such as postCSS, but is there a requirement that some styles can be directly written in the STYLE of XML tag, and then can be processed, for example, PX2REM can convert PX to REM, Is it possible to write in style?

Train of thought

We in webpack, /. (js | JSX)? $/ Add a loader before babel-loader (webpack from right to left) to replace the px that needs to be changed

code

const loaderUtils = require('loader-utils');

// Default parameters
const defaultopts = {
    remUnit: 100.// rem unit value (default: 100)
    remFixed: 2.// rem value precision (default: 2)
};
// Get webPack configured parameters
const opts = loaderUtils.getOptions(this);
// Combine the parameters
const config = Object.assign({}, defaultopts, opts);
const ZPXRegExp = /\b(\d+(\.\d+)?) SUPX\b/;

module.exports = function (source) {
    let pxGlobalRegExp = new RegExp(ZPXRegExp.source, 'g');
    if (this.cacheable) {
        this.cacheable();
    }
    // Test if there is a match and then replace it
    if (pxGlobalRegExp.test(source)) {
        return source.replace(pxGlobalRegExp, ($0, $1) = > {let val = $1 / config.remUnit;
            // Down to a few digits
            val = parseFloat(val.toFixed(config.remFixed));
            return val === 0 ? val : val + 'rem';
        });
    } else {
        returnsource; }};Copy the code

usage

{
    loader: path.join(rootPath, 'loaders/jsxPx2RemLoader'),
    options: {
        remUnit: 100,
        remFixed: 3
    }
}
Copy the code

The source code

The source code

appreciates

If you think my writing is helpful to you, please give me some sponsorship, thank you very much