Emotion 和 Linaria 是两个 CSS in JS 方案, API 相近.
项目里有特殊的场景, 但愿能减少体积, 咱们一向基于 Emotion 比较大,css
咱们的 Emotion 如今都是跟着 JavaScript 走到, 没有作 CSS 分离,
以前尝试过生产环境分离 CSS, 可是由于 CSS 规则顺序问题, 效果不够可控,
加上不想在 TypeScript 后面套一层 Babel, 这条路也就不想走了.
因此目前打包的 JavaScript 里面就有图片上这么大的 Emotion 代码的体积.前端
justineo 提醒我说 Emotion 能够用 Linaria 替换, 我就去看了一下.
这个库的 API 基本上跟 Emotion 一致, 咱们的写法大体用到了,node
import {css, cx} from "emotion" let styleA = css` color: red; `;
在 Linaria 当中基本上无缝替换了,webpack
import {css, cx} from "linaria" let styleA = css` color: red; `;
另外我关注的 prefix vendor, 在 linaria 里边同样也是有支持的.
其余的 API 应该也出跟着 style-components 的方案一致的.git
跟 Emotion 相比, linaria 有个比较完善的静态的 css 分离的功能.github
https://callstack.com/blog/ho...web
In short, CSS in JS libraries such as Emotion and Styled Components parse and apply your styles when your page loads in the browser, Linaria extracts the styles to CSS files when you build your project (e.g. with webpack), and the CSS files are loaded normally.Emotion used to have a static extraction mode, which was limited in the sense that it doesn’t support interpolations in the CSS string and can’t use many of Emotion’s features. Linaria will evaluate the interpolations such as JavaScript variables and functions in the CSS string at build time.babel
推测是去掉了 Emotion 某些动态的特性的支持把, 方便分离 CSS.
分离的过程是经过 Babel 完成的, 因此在特殊的场景当中我仍是须要 Babel.app
这个修改增长了几个相关依赖,工具
"babel-loader": "^8.0.6", "linaria": "^1.3.1", "core-js": "^2.6.5", "string-replace-loader": "^2.2.0",
core-js
须要锁定版本, 太高的版本由于不兼容是出现了报错的.
string-replace 是为了处理依赖当中引用了 Emotion 的代码.
项目当中的代码我能够手动更改, 可是依赖组件由于其余项目复用, 很差直接改掉,
经过 Webpack 增长配置, 把 Emotion 的依赖都指向 Linaria(不必定须要):
resolve: { alias: { emotion: "linaria" } },
而后考虑到依赖代码引用得早, 仍是要经过字符串替换把已有的引用提前替换掉:
test: /\.js?$/, use: [ { loader: "string-replace-loader", options: { search: `"emotion"`, replace: `"linaria"` } } ]
其余的部分主要靠 Linaria 本身的工具配合 Babel 去搞了.
loader: require.resolve("linaria/loader")
我这边 CSS 最终没有分离出去, 由于需求方面要打成一个 js 的包, 因此仍是用 style 标签运行.
打包之后带着 style-loader
跟 css-loader
的代码会显得比较大一点,
另外也要增长配置让 Webpack 去掉 Node 相关的代码, 不须要打包进来:
node: false,
而 CSS 部分的代码, 被 Linaria 处理, 单独以 CSS 文件的形式存在了.
道理讲应该是还能够去掉 style-loader 等等, 直接把 CSS 引入标签当中,
没想好建构方面怎么处理, 暂时先无论了.
总体处理下来, Emotion 换上了 style-loader 等, 体积减少 20k,
压缩之后大体上也就是 2k 多一些, 跟预想的仍是能够的.
可是若是能有办法把 style-loader 部分也简化掉, 还能减少一些, 再找找建构方案...
其余关于积梦前端的模块和工具能够查看咱们的 GitHub 主页 https://github.com/jimengio .
目前团队正在扩充, 招聘文档见 GitHub 仓库 https://github.com/jimengio/h... .