2020-07-14 21:41:07
在 Sass 中双亲选择器(Parent Selector 有时也叫父选择器) &
是一个十分有用且常用的选择器,它可以复用外部选择器的名字,从而更轻松地实现多重样式编写。
.btn {
background: transparent;
&:hover {
background: grey;
}
}
会输出
.btn {
background: transparent;
}
.btn:hover {
background: grey;
}
有时候我们遇到这样一种模式,如主题样式,在元素根处可能有 .dark-theme
来说明目前处于黑暗模式;或者使用 Modernizr 检测浏览器特性,在根元素会根据环境添加相应 class 表示特性支持情况。这时候我们写样式可能就需要拆分开来写。
.btn {
background: transparent;
&:hover {
background: grey;
}
}
.dark-theme .btn { background: linear-gradient(cornflowerblue, rebeccapurple);}
这里有两点不太舒服的地方:
我们来看看如何解决这两个痛点。
在 Sass 中有一个 at 规则叫 @at-root
,它可以跳出当前嵌套直接在文档根输出内容。
.btn {
background: transparent;
&:hover {
background: grey;
}
@at-root .dark-theme & { background: linear-gradient(cornflowerblue, rebeccapurple); }}
会输出
.btn {
background: transparent;
}
.btn:hover {
background: grey;
}
.dark-theme .btn {
background: linear-gradient(cornflowerblue, rebeccapurple);
}
但这里依然没有解决祖先选择器名耦合的问题,于是我们进一步抽象。
将以上用法封装为 mixin 即可达到复用。
@mixin dark-theme {
@at-root .dark-theme & {
@content;
}
}
.btn {
background: transparent;
&:hover {
background: grey;
}
@include dark-theme {
background-image: linear-gradient(cornflowerblue, rebeccapurple);
}
}
一些过渡库,如 Vue transition 和 React Transition Group 会设置一系列的类型名,如 .fade-enter
、.fade-exit
,在 Sass 中我们可以直接拼接 &-enter
进行复用,现在让我们的 mixin 也支持:
@mixin dark-theme($modifiers...) {
@if length($modifiers) > 0 {
@each $modifier in $modifiers {
@at-root .dark-theme &#{$modifier} {
@content;
}
}
} @else {
@at-root .dark-theme & {
@content;
}
}
}
.btn {
background: transparent;
&:hover {
background: grey;
}
@include dark-theme {
background: linear-gradient(cornflowerblue, rebeccapurple);
}
@include dark-theme(-enter) {
background: cornflowerblue;
}
@include dark-theme(-enter-active, -exit) {
background: rebeccapurple;
}
}
输出
.btn {
background: transparent;
}
.btn:hover {
background: grey;
}
.dark-theme .btn {
background: linear-gradient(cornflowerblue, rebeccapurple);
}
.dark-theme .btn-enter {
background: cornflowerblue;
}
.dark-theme .btn-enter-active {
background: rebeccapurple;
}
.dark-theme .btn-exit {
background: rebeccapurple;
}
可以看到 @include dark-theme(-enter-active, -exit)
在多个修饰符的情况下生成了单独的重复内容。
要去掉重复我们可以直接拼接选择器。
@mixin dark-theme($modifiers...) {
@if length($modifiers) > 0 {
$selectors: ();
@each $modifier in $modifiers {
$selectors: append(
$selectors,
#{".dard-theme "}#{&}#{$modifier},
comma
);
}
@at-root #{$selectors} {
@content;
}
} @else {
@at-root .dark-theme & {
@content;
}
}
}
输出
.btn {
background: transparent;
}
.btn:hover {
background: grey;
}
.dark-theme .btn {
background: linear-gradient(cornflowerblue, rebeccapurple);
}
.dard-theme .btn-enter {
background: cornflowerblue;
}
.dard-theme .btn-enter-active, .dard-theme .btn-exit { background: rebeccapurple;}
最后我们将这个模式再进一步抽象出来,成为通用的 at-root
mixin。
@mixin at-root($ancestor, $modifiers...) {
@if length($modifiers) > 0 {
$selectors: ();
@each $modifier in $modifiers {
$selectors: append(
$selectors,
#{$ancestor}#{" "}#{&}#{$modifier},
comma
);
}
@at-root #{$selectors} {
@content;
}
} @else {
@at-root #{$ancestor} & {
@content;
}
}
}
现在 dark-theme
可以这么定义。
@mixin dark-theme($modifiers...) {
@include at-root('.dark-mode', $modifiers...) {
@content;
}
}
通过封装 mixin 我们可以方便地在规则内部直接引用祖先选择器定义规则,同时摆脱与祖先类型名的耦合,使到代码可以灵活应对变更。
2020-07-09 02:58:12
Use neutrino-webextension which works out of the box.
Read on if you are interested in the theory behind the scene.
There is a browser.management
API which is used by many extension-livereload extensions. But looks like it does not work when manifest.json
changes.
Instead we use another API browser.runtime.reload()
which reloads the extension itself.
How do we know when to reload? It should happens after file changes. If using bundler there usually be hooks for performing jobs after bundling. Otherwise take a look at fs.watch or node-watch.
How does the extension know when to reload itself? It is not ideal using WebSocket or extension messaging API which involves native setups. Instead we try to leverage the browser extension API itself.
The idea is that the extension monitors web requests for a special url. Whenever the browser requests this url the extension gets notified and performs reloading logic.
This is an example project structure for the sake of this post.
project/
├── livereload
│ ├── background.js
│ ├── livereload.html
│ └── livereload.js
├── src
│ ├── background
│ │ └── index.js
│ └── popup
│ ├── index.html
│ └── index.js
└── manifest.json
First we need to be able to redirect web requests.
{
"background": {
"persistent": true,
"scripts": [
"livereload/background.js",
"src/background/index.js"
]
},
"permissions": [
"*://neutrino-webextension.reloads/*",
"webRequest",
"webRequestBlocking"
],
"web_accessible_resources": [
"livereload/*"
]
}
http://neutrino-webextension.reloads
is the special url that we are going to monitor.
const b = typeof browser === 'undefined' ? chrome : browser
b.webRequest.onBeforeRequest.addListener(
() => ({ redirectUrl: b.runtime.getURL('livereload/livereload.html') }),
{
urls: ['*://neutrino-webextension.reloads/*'],
types: ['main_frame']
},
['blocking']
)
It will redirect the request to livereload/livereload.html
.
We first send a message to background, then close the page immediately.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Reload</title>
</head>
<body>
<script src="./livereload.js"></script>
</body>
</html>
Script has to be in separate file.
const b = typeof browser === 'undefined' ? chrome : browser
b.runtime.sendMessage('_neutrino-webextension.reloads_')
if (window.history.length <= 1) {
window.close()
} else {
history.back()
}
In background we listen to the messages and perform reloading.
const b = typeof browser === 'undefined' ? chrome : browser
b.webRequest.onBeforeRequest.addListener(
() => ({ redirectUrl: b.runtime.getURL('livereload/livereload.html') }),
{
urls: ['*://neutrino-webextension.reloads/*'],
types: ['main_frame']
},
['blocking']
)
b.runtime.onMessage.addListener(message => { if (message === '_neutrino-webextension.reloads_') { b.runtime.reload() }})
So far so good! Except there is one tiny issue. The redirection will leave browsing histories in the browser. Let's remove it!
{
"background": {
"persistent": true,
"scripts": [
"livereload/background.js",
"src/background/index.js"
]
},
"permissions": [
"browsingData", "*://neutrino-webextension.reloads/*",
"webRequest",
"webRequestBlocking"
],
"web_accessible_resources": [
"livereload/*"
]
}
Remove before reloading.
const b = typeof browser === 'undefined' ? chrome : browser
b.webRequest.onBeforeRequest.addListener(
() => ({ redirectUrl: b.runtime.getURL('livereload/livereload.html') }),
{
urls: ['*://neutrino-webextension.reloads/*'],
types: ['main_frame']
},
['blocking']
)
b.runtime.onMessage.addListener(message => {
if (message === '_neutrino-webextension.reloads_') {
b.browsingData.remove( { hostnames: [ 'neutrino-webextension.reloads' ], originTypes: { unprotectedWeb: true, protectedWeb: true }, since: Date.now() - 2000 }, { history: true } ) b.browsingData.remove( { originTypes: { extension: true }, since: Date.now() - 2000 }, { history: true } )
b.runtime.reload()
}
})
This will remove the history of the special url and the livereload.html
.
To open the brower with the special url:
npm install --save-dev open
After file changes, call
open('http://neutrino-webextension.reloads')
// specify browser
open('http://neutrino-webextension.reloads', { app: 'firefox' })
// with arguemnts
open(
'http://neutrino-webextension.reloads',
{
app: ['google-chrome', '--profile-directory=Profile 1']
}
)
The extension should recognise the request and reload itself.
Even though it works, this is still a lot of work to setup if implementing manually. It is recommended use a preset like neutrino-webextension which is battery included.
2020-07-01 00:20:16
自宣布一年多过去 React 并发模式(Concurrent Mode)依然在实验阶段,但早期生态已悄然在形成。Concurrent Mode 这个词越来越频繁出现各种 React 库的介绍和讨论中。作为库开发者或者正打算开发 React 库的朋友,现在开始测试并发模式安全能避免日后可能出现的许多隐性问题,同时这也是一个很好的招牌。
注意:本文内容比较前沿,请留意文章的时限,以下的内容随时均可能发生改变。
目前只有 @experimental 版本的 React 才支持开启并发模式,考虑到稳定性,我们更希望尽量用稳定版 React 测试其它功能,只用实验版 React 测试并发模式下的功能。
yarn add --dev experimental_react@npm:react@experimental experimental_react-dom@npm:react-dom@experimental experimental_react-test-renderer@npm:react-test-renderer@experimental
如此我们安装实验版本并加上了 experimental_
前缀的别名。选择前缀而不是后缀是为了方便日后统一去除。
React 通过 scheduler
这个模块来进行调度,并提供了 jest-mock-scheduler
来在测试时 mock 掉。目前 jest-mock-scheduler
仅仅是导出了 scheduler/unstable_mock.js
,所以不装也可以,React 内部也是直接引用 scheduler/unstable_mock.js
,但考虑到未来兼容,还是建议安装 jest-mock-scheduler
。
yarn add --dev jest-mock-scheduler
测试文件中:
let Scheduler
let React
let ReactTestRenderer
let act
let MyLib
describe('Concurrent Mode', () => {
beforeEach(() => {
jest.resetModules()
jest.mock('scheduler', () => require('jest-mock-scheduler'))
jest.mock('react', () => require('experimental_react'))
jest.mock('react-dom', () => require('experimental_react-dom'))
jest.mock('react-test-renderer', () => require('experimental_react-test-renderer'))
MyLib = require('../src')
React = require('react')
ReactTestRenderer = require('react-test-renderer')
Scheduler = require('scheduler')
act = ReactTestRenderer.act
})
})
如果用 TypeScript 写测试,那么
let Scheduler: import('./utils').Scheduler
let React: typeof import('react')
let ReactTestRenderer: typeof import('react-test-renderer')
let act: typeof import('react-test-renderer').act
let MyLib: typeof import('../src')
其中 scheduler
mock 的类型目前先手动补上,见这里。
React 内部使用了许多自定义断言,为了减少使用难度,这里我们参考同样的方式扩展 Jest expect
。
在 jest.config.js
中添加 setupFilesAfterEnv
指定配置文件,如 setupFilesAfterEnv: [require.resolve('./scripts/jest-setup.js')]
,自定义断言参考这里。
如果用 TypeScript 写测试,那么还需要添加 expect-extend.d.ts
,参考这里。
Scheduler mock 掉之后多了许多控制调度的方法。基本逻辑是默认所有调度都只会累积而不处理,通过手动 flush
或者 act
清理。
通过 yeildValue
记录锚值,然后 flush
的时候可以选择只清理到特定锚值的地方,相当于打断点。在断点处我们可以做各种额外的处理以测试我们的库是否会出现异常。
并发模式下的一个常见问题是状态出现断裂(tearing)。这通常出现在依赖外部模块或者 ref
管理状态。当组件渲染暂停时,如果外部状态发生了变化,该组件恢复渲染后将使用新的值进行渲染,但其它组件却可能在之前已经用了旧的值渲染,故出现了断裂。
要测试我们的库会不会产生断裂现象,我们可以在组件渲染结束前打一个点,到断点后触发外部状态变化,然后检查组件状态是否准确。
如一个捏造的监听任意 input
元素值的 hook,
const useInputValue = input => {
const [value, setValue] = React.useState('A')
React.useEffect(() => {
const callback = event => {
setValue(event.currentTarget.value)
}
input.addEventListener('change', callback)
return () => input.removeEventListener('change', callback)
}, [input])
return value
}
为了测试这个 hook 会不会产生断裂,我们设置两个组件监听同个数据源,中断一个组件的渲染,同时数据源产生新值,再恢复组件渲染并对比两个组件结果是否相同。
it('should should not tear', () => {
const input = document.createElement('input')
const emit = value => {
input.value = value
input.dispatchEvent(new Event('change'))
}
const Test = ({ id }) => {
const value = useInputValue(input)
// 打点
Scheduler.unstable_yieldValue(`render:${id}:${value}`)
return value
}
act(() => {
ReactTestRenderer.create(
<React.Fragment>
<Test id="first" />
<Test id="second" />
</React.Fragment>,
// 启用并发模式
{ unstable_isConcurrent: true }
)
// 初次渲染
expect(Scheduler).toFlushAndYield(['render:first:A', 'render:second:A'])
// 检查正常修改渲染
emit('B')
expect(Scheduler).toFlushAndYield(['render:first:B', 'render:second:B'])
// 这次渲染到第一个组件后停止
emit('C')
expect(Scheduler).toFlushAndYieldThrough(['render:first:C'])
// 同时产生新值
emit('D')
expect(Scheduler).toFlushAndYield([
'render:second:C',
'render:first:D',
'render:second:D'
])
})
})
最后两者均渲染 D
,故使用该 hook 没有断裂问题。
2020-03-30 01:04:45
由于浏览器扩展有特殊的权限限制,许多前端的开发工具都无法直接派上用场,如之前我解决了热更新和分块自动填写到清单的问题。现在我们继续突破下个影响性能的问题:动态加载分块。
Webpack 支持 import()
自动分块并异步加载,这对于大型应用来说是非常有用的功能。虽然浏览器扩展的源文件都在本地,但对于大型应用来说静态加载依然会浪费了不少内存。那么为什么浏览器扩展不支持异步加载呢?这就需要理解 Webpack 是怎么处理的。
(如果只关心如何在浏览器扩展中使用,本文的内容已封装为 webpack-target-webextension 库。)
当我们指定(或默认) Webpack Target 为 web
的时候,Webpack runtime 会以 JSONP 方式来加载异步块。那么什么是 JSONP?
JSONP 常用于跨域动态获取数据。如 a.com
向 b.com
请求数据,
myCallback
;myCallback
实现加载数据的逻辑;myCallback
作为参数构造请求链接,如 https://b.com/data?callback=myCallback
;<script>
标签发起请求,<script src="https://b.com/data?callback=myCallback"></script>
;myCallback(...)
;myCallback
的逻辑被执行。这种方式为什么在浏览器扩展中会失效呢?我们都知道一些浏览器扩展可以对用户的网页进行修改,如美化或者去广告。这些修改是通过一种叫 content script 类型的脚本实现。每个 content script 可以在作者指定的时机被植入到页面上。虽然 content script 可以修改 DOM,但是 content script 本身是运行在隔离的沙箱环境中的。这个环境可以让 content script 访问部分浏览器扩展 API。
所以当 Webpack 以 JSONP 方式加载异步块的时候,<script>
中的回调会在用户的脚本环境中执行,而扩展环境中的接收回调只能默默等待到超时。
主流浏览器早早就支持了原生的 import()
,那么有没有可能,我们不让 Webpack 生成 JSONP 而直接使用原生的 import()
? CRIMX 说 yes!
在 Webpack 中,模块加载的逻辑通过 target
设置来调整。Webpack 4 中预设了几种常见的 target:
Option | Description |
---|---|
async-node | 用于类 Node.js 环境 |
electron-main | 用于 Electron 主进程 |
electron-renderer | 用于 Electron 渲染进程 |
electron-preload | 用于 Electron 渲染进程 |
node | 用于类 Node.js 环境 |
node-webkit | 用于 NWebKit 环境 |
web | 用于类浏览器环境 |
webworker | 用于 WebWorker |
很可惜这几种都不支持原生 import()
,也不适用浏览器扩展。在 Webpack 5 的预览中明确提到了对 es2015 的支持,同时提供了新的 module
设置。但是离 Webpack 5 正式发布以及生态跟上可能还有一段时间。
最后 target
还支持传入函数以自行实现逻辑。尽管 Webpack 的源码不是很好读,最后还是决定挑战一下,自定义实现一个针对浏览器扩展的 target
。
首先通过文档找到判断上面预设环境的位置。通过参考 web 的配置可以找到 JSONP 的实现在 JsonpMainTemplatePlugin.js 中。
其中异步块的加载分了三种方式,正常的,预加载的以及预读取的,对应 <script>
和 <link>
的 preload
和 prefetch
。全部改成 import()
即可。
其中注意计算块的路径,由于在 content script 中相对路径会根据当前页面计算,而我们需要根据扩展根来算路径。所以函数 jsonpScriptSrc
改为
if (needChunkOnDemandLoadingCode(chunk)) {
extraCode.push(
'',
'// script path function',
'function webextScriptSrc(chunkId) {',
Template.indent([
`var publicPath = ${mainTemplate.requireFn}.p`,
`var scriptSrcPath = publicPath + ${getScriptSrcPath(
hash,
chunk,
'chunkId'
)};`,
`if (!publicPath || !publicPath.includes('://')) {
return (typeof chrome === 'undefined' ? browser : chrome).runtime.getURL(
scriptSrcPath
);
} else {
return scriptSrcPath;
}`
]),
'}'
)
}
从而利用 runtime.getURL
来计算扩展资源路径。
可以通过 publicPath
来控制根路径。
注意去除 @babel/plugin-syntax-dynamic-import
等插件以免 import()
被转换掉。
Webpack 一些设置的默认值依赖 target
来判断,所以需要手动设置:
module.exports = {
resolve: {
mainFields: ['browser', 'module', 'main'],
aliasFields: ['browser']
},
output: {
globalObject: 'window'
}
}
完整修改见这里。
2020-02-26 01:58:01
(This post is also on medium)
Stateful logic is unavoidable in any React project. In early days we used the state
property in Class-Components to hold stateful values.
But quickly we realized that it is prone to lose track of states in "this" way. So we divided Components into stateful(smart) Components and stateless(dumb) Components. Stateful logic is delegated to parent stateful Components to keep most Components stateless.
This does not solve the issue, just makes it less painful.
Then came the age of Redux(and MobX etc.). We started to put states into central stores which can be tracked with devtools and stuff.
This does not solve the issue, just delegates it to outside stores.
Introducing stores is acceptable for a full project but would be too bloated for developing reusable stateful Components.
React Hooks fills this gap by offering a mechanism that connects side-effects separately within the Component.
For stateful logic it is like connecting to many mini-stores within the Component. Side-effect code with hooks is compact, reusable and testable.
Hooks is an attempt to solve the issue. It is delicate and not perfect but it is the best we have so far.
For more about hooks see the React Docs.
Since React hooks opens a door of reusing side-effect logic within Components, it is tempting to reuse complicated asynchronous logic like remote data fetching, intricate animation or device input sequence interpretation.
One of the most popular ways to manage complicated asynchronous logic is Reactive Programming, a language-independent declarative programming paradigm concerned with data streams and the propagation of change. RxJS, part of the ReactiveX(Reactive Extensions), is a JavaScript implementation of reactive programming.
There are also libraries that focus only on a few specific asynchronous scenarios, like swr for remote data fetching. This is like comparing Redux Saga with Redux Observable. The knowledge you gain from learning how to use these libraries is not as transferable as RxJS and Reactive Programming.
Yes there is a learning curve on RxJS but that is mostly a one-time conceptual thing. Don't be scared by the number of RxJS opertators. You most likely only need a few of them. Also see the Operator Decision Tree.
We first tried rxjs-hooks but quickly encountered some tricky TypeScript issues. We also think the useEventCallback
is taking too much responsibilities which is a performance issue that is hard to fix due to rules of hooks.
Unfortunately the project is not actively developed as the team has shifted focus to the redux-observable-like ayanami project.
Ultimately we rethought the whole integration, redesigned API from the ground up and created observable-hooks for connecting RxJS Observable to React Components.
A simple example(more on the docs):
import React from 'react'
import { useObservableState } from 'observable-hooks'
import { timer } from 'rxjs'
import { switchMap, mapTo, startWith } from 'rxjs/operators'
const App = () => {
const [isTyping, updateIsTyping] = useObservableState(
event$ => event$.pipe(
switchMap(() =>
timer(1000).pipe(
mapTo(false),
startWith(true)
)
)
),
false
)
return (
<div>
<input type="text" onKeyDown={updateIsTyping} />
<p>{isTyping ? 'Good you are typing.' : 'Why stop typing?'}</p>
</div>
)
}
By decoupling states, events and Observables it no longer makes unused resources run idle.
Logic lives in pure function which improves reusability and testability.
See the docs for more about core concepts and API.
Pomodoro Timer Example:
With the experimental React Suspense asynchronous resources can be read declaratively like it has already been resolved.
Since Suspense is just a mechanism it is possible to convert Observables into Suspense compatible resources (benefits of observable as data source).
Observable-hooks offers ObservableResource
to do the trick.
// api.js
import { ObservableResource } from 'observable-hooks'
const postResource$$ = new Subject()
export const postsResource = new ObservableResource(postResource$$.pipe(
switchMap(id => fakePostsXHR(id))
))
export function fetchPosts(id) {
postResource$$.next(id)
}
Resources are consumed with useObservableSuspense
.
// App.jsx
import { useObservableSuspense } from 'observable-hooks'
import { postsResource, fetchPosts } from './api'
fetchPosts('crimx')
function ProfilePage() {
return (
<Suspense fallback={<h1>Loading posts...</h1>}>
<ProfileTimeline />
</Suspense>
)
}
function ProfileTimeline() {
// Try to read posts, although they might not have loaded yet
const posts = useObservableSuspense(postsResource)
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.text}</li>
))}
</ul>
)
}
The API of observable-hooks is really simple and flexible. Folks who love both React and RxJS I highly recommend you give it a try.
What do you think? Please let us know by leaving a comment below!