For less files that use @import internally to introduce third-party libraries, less.render fails to compile

background

Recently, I am working on an antd-based business component library. Since the tree-shaking function of esmodule is to be implemented, the implementation of this function code does not depend on third-party construction tools. It is completely manually coded by using node + babel. Some questions are specially recorded, one is to be able to review in the future to avoid forgetting; the other is to communicate with other development students.

code display

First, let's paste the specific code display

This is the less.render method to convert less into css

less.render(
                fs.readFileSync(filePath).toString(),
                {
                    compress: true,
                },
                // eslint-disable-next-line func-names
                function (e, output) {
                    fs.removeSync(filePath)
                    fs.outputFileSync(filePath.replace(lessRegExp, '.css'), output.css)
                }
            )

And my less file uses antd's third-party less library

@import '~antd/dist/antd.less';

Cause & Solution

When using less.render for conversion, it cannot find the path represented by the special character '~', which is supported internally by some packaging tools such as webpack, rollup, and glup.

Therefore, the `~` symbol needs to be removed. Secondly, since the less.render method cannot convert the internal @import less syntax, we directly import the antd css library.

We use the following import method instead:

@import 'antd/dist/antd.css';

flaws

There is no problem after I tried it, but later I found that due to the relative path of @import 'antd/dist/antd.css'; this kind of use, there is no problem in packaging under the construction tools such as webpack used by user projects. Because webpack finds that all business modules do not find this path, it will go to node_modules to find it.

However, when the user manually packs the package, an error that the path cannot be found will still be reported.

think

Since the component library itself is re-encapsulated based on antd, I thought about it carefully. Since antd is used, the user needs to introduce the global antd style file in the project used. There are two reasons: 1. Antd style The volume is large, and the introduction will cause the volume of the component library to increase. 2. Antd itself does the same. If the user project imports antd style files, the files will be duplicated at this time.

in conclusion

Based on the above personal thinking, there is no need to introduce antd style files in the component library

Guess you like

Origin blog.csdn.net/u014165391/article/details/125197242