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... .