{"id":18886381,"url":"https://github.com/fengzilong/cheatsheet","last_synced_at":"2026-02-05T22:31:40.543Z","repository":{"id":85797534,"uuid":"61265815","full_name":"fengzilong/cheatsheet","owner":"fengzilong","description":":bulb: cheatsheet for efficiency and some tricks","archived":false,"fork":false,"pushed_at":"2019-05-16T10:49:41.000Z","size":104,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-02T21:50:27.878Z","etag":null,"topics":["cheatsheet","tricks"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fengzilong.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-06-16T05:51:24.000Z","updated_at":"2019-05-16T10:49:43.000Z","dependencies_parsed_at":"2023-03-13T06:44:44.831Z","dependency_job_id":null,"html_url":"https://github.com/fengzilong/cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/fengzilong/cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fengzilong%2Fcheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fengzilong%2Fcheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fengzilong%2Fcheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fengzilong%2Fcheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fengzilong","download_url":"https://codeload.github.com/fengzilong/cheatsheet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fengzilong%2Fcheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29136763,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-05T21:59:57.939Z","status":"ssl_error","status_checked_at":"2026-02-05T21:59:57.628Z","response_time":65,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","tricks"],"created_at":"2024-11-08T07:27:06.290Z","updated_at":"2026-02-05T22:31:40.526Z","avatar_url":"https://github.com/fengzilong.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# cheatsheet\n\n\u003e cheatsheet for efficiency and some other tricks\n\n\u003c!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 --\u003e\n\n- [cheatsheet](#cheatsheet)\n\t- [Shortcuts](#shortcuts)\n\t\t- [Chrome](#chrome)\n\t\t- [Atom](#atom)\n\t\t- [Photoshop](#photoshop)\n\t\t- [Windows Explorer](#windows-explorer)\n\t- [Windows Tricks](#windows-tricks)\n\t\t- [open cmd in current folder](#open-cmd-in-current-folder)\n\t\t- [files in node modules can not be deleted](#files-in-node-modules-can-not-be-deleted)\n\t\t- [create .xxx file](#create-xxx-file)\n\t- [NVM](#nvm)\n\t\t- [list all available node versions](#list-all-available-node-versions)\n\t\t- [use specific node version](#use-specific-node-version)\n\t- [NPM](#npm)\n\t\t- [auth](#auth)\n\t\t- [release new version](#release-new-version)\n\t\t- [check for outdated dependencies](#check-for-outdated-dependencies)\n\t\t- [install](#install)\n\t\t- [show detail during installation](#show-detail-during-installation)\n\t- [Atom Package](#atom-package)\n\t\t- [auth](#auth)\n\t\t- [release new version](#release-new-version)\n\t\t- [install your starred packages](#install-your-starred-packages)\n\t\t- [install other user's starred packages](#install-other-users-starred-packages)\n\t- [Package.json](#packagejson)\n\t\t- [dependencies version](#dependencies-version)\n\t- [Git](#git)\n\t\t- [push local folder to github](#push-local-folder-to-github)\n\t\t- [push and set upstream](#push-and-set-upstream)\n\t- [GitHub](#github)\n\t\t- [search something in certain path in repo](#search-something-in-certain-path-in-repo)\n\t- [Electron](#electron)\n\t\t- [prevent redirect when drop files into electron window](#prevent-redirect-when-drop-files-into-electron-window)\n\t\t- [can't find module xxx after packaging](#cant-find-module-xxx-after-packaging)\n\t\t- [launch at login](#launch-at-login)\n\t- [JavaScript Snippets](#javascript-snippets)\n\t\t- [how to slice arguments without leaking them](#how-to-slice-arguments-without-leaking-them)\n\t\t- [fast bind](#fast-bind)\n\t\t- [play sound from arraybuffer](#play-sound-from-arraybuffer)\n\t\t- [escape regexp](#escape-regexp)\n\t\t- [log some variables in format](#log-some-variables-in-format)\n\t- [CSS Snippets](#css-snippets)\n\t\t- [auto fit content width](#auto-fit-content-width)\n\n\u003c!-- /TOC --\u003e\n\n## Shortcuts\n\n### Chrome\n\n```\nctrl + L 聚焦地址栏\nctrl + T 打开一个新的标签页\nctrl + D 收藏当前页面至书签\nctrl + J 打开下载\nctrl + H 打开浏览历史\nctrl + P 打印当前页面，可保存pdf\nctrl + N 打开新的窗口\nctrl + shift + N 打开隐身模式窗口\nctrl + shift + Tab 切换至上一个标签页\nctrl + Tab 切换至下一个标签页\nctrl + W 关闭当前标签页\nctrl + shift + W 关闭所有标签页\nctrl + shift + T 恢复标签页\nctrl + shift + I 切换Elements面板\nctrl + shift + J 切换Console面板\nctrl + [ 切换至上一个面板(开发者工具打开)\nctrl + ] 切换至下一个面板(开发者工具打开)\nctrl + shift + M 切换手机模式(开发者工具打开)\nctrl + shift + C 选择页面元素(开发者工具打开)\nShift + 点击Elements面板侧边栏中的某个色值，切换颜色格式\nCtrl + 点击Elements面板侧边栏的某个样式，寻找样式所在文件位置\nAlt + \u003c- 后退\nAlt + -\u003e 前进\nCommand + Option + F 在所有源码中查找\n```\n\n### Atom\n\n```\nctrl + shift + \\ 在treeview中找到当前文件\nctrl + \\ 切换treeview\nctrl + alt + I 打开Devtools\nctrl + D 选中下一个内容相同的选区\nA 新建文件(选中treeview中的某个目录后)\nshift + A 新建文件夹(选中treeview中的某个目录后)\nD 复制当前文件到当前目录\nctrl + P 模糊查找\nctrl + shift + P atom中所有的命令\nctrl + , 打开setting\nctrl + G 跳转到指定行\u0026列\nctrl + alt + Q 合并成一行\nctrl + shift + F2 清除所有书签\n```\n\n以下是自行覆盖的快捷键，请无视\n\n```\nctrl + F2 toogle书签\nF2 下一个书签\nshift + F2 上一个书签\n```\n\n### Photoshop\n\n```\nC 裁剪\nV 选择\nM 选区\nSpace 移动\nctrl + shift + alt + S 保存png等格式\nctrl + G 分组\nctrl + shift + I 反选选区\nctrl + shift + V 原位置粘贴\nctrl + T 形变\nctrl + E 合并选中的图层(如果合并后的图层有问题，请先尝试栅格化待合并的图层)\nctrl + 鼠标点击图层 选中当前图层像素对应的选区\nalt + 鼠标点击图层左侧的`眼睛` solo当前图层\nalt + 鼠标点击蒙版 编辑蒙版\n```\n\n### Windows Explorer\n\n```\nctrl + L 聚焦地址栏\nctrl + W 关闭当前窗口\nctrl + shift + N 新建文件夹\nwin + E 打开一个新的资源管理器\n```\n\n## Windows Tricks\n\n### open cmd in current folder\n\n- ctrl + shift + R(需要安装Listary)\n- 在资源管理器的地址栏输入cmd并回车\n- 按住shift，在文件夹空白处右键，右键菜单中会出现“在此处打开命令行窗口”\n\n### force delete files in node_modules\n\n- 最笨的办法，进入目录里面，剪切至路径较浅的目录再删除\n- mkdir tmp \u0026\u0026 robocopy tmp node_modules /purge\n- `npm i nmd-cli -g`，在node_modules所在文件夹执行nmd即可\n\n### create .xxx file\n\n- 假如你要输入的文件名是`.dev`，输入文件名`.dev.`，回车即可\n\n## NVM\n\n### list all available node versions\n\n```bash\n$ nvm list\n```\n\n### use specific node version\n\n```bash\n$ nvm use \u003cversion\u003e\n```\n\n## chrome\n\n### chrome offline dinosaur game\n\nchrome://dino/\n\n## yrm\n\n### install yrm\n\n```bash\n$ npm i -g yrm\n```\n\n### list\n\n```bash\n$ yrm ls\n```\n\n### use\n\n```bash\n$ yrm use taobao # use taobao registry\n$ yrm use npm # use npm registry\n```\n\n## NPM\n\n### auth\n\n```bash\n$ npm whoami\n$ npm login # or npm adduser\n```\n\n### release new version\n\n```bash\n$ npm version patch/minor/major\n$ npm publish\n```\n\n### check for outdated dependencies\n\n```bash\n$ npm outdated\n```\n\n### install\n\n```bash\n$ npm i \u003cpackageName\u003e [-S/-D]\n```\n\n### show detail during installation\n\n```bash\n$ npm i \u003cpackageName\u003e -d\n```\n\n### package searching strategy in npm scripts\n\ne.g.\n```json\n{\n\t\"scripts\": {\n\t\t\"dev\": \"onchange ...\"\n\t}\n}\n```\nnpm adds `node_modules/.bin` for searching `onchange` package, it means you don't have to write the `node_modules/.bin` prefix\n\n\u003e In addition to the shell's pre-existing PATH, npm run adds node_modules/.bin to the PATH provided to scripts. Any binaries provided by locally-installed dependencies can be used without the node_modules/.bin prefix\n\n参考：https://docs.npmjs.com/cli/run-script\n\n### custom arguments when executing npm scripts\n\n```bash\n$ npm run test -- --grep=\"pattern\"\n```\n\n\u003e As of npm@2.0.0, you can use custom arguments when executing scripts. The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script\n\n\u003e The arguments will only be passed to the script specified after npm run and not to any pre or post script\n\n参考：https://docs.npmjs.com/cli/run-script\n\n### install from local folder as dependency\n\nnpm 2.0.0 [supports specifying local dependencies in your package.json](https://docs.npmjs.com/files/package.json#local-paths):\n\n\u003e npm install --save ../apple\n\u003e cat package.json\n{\n  \"name\": \"bowl\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"apple\": \"file:../apple\"\n  }\n}\nnpm install will copy (and npm install) the package into the target's node_module's hierarchy.\n\nThis is not an ideal workflow during development: any time you modify your local dependency, you must reinstall it in every location that depends on it. If you do not update all copies, you will have different versions of the same code, probably under the same version number.\n\n本地有两个npm packages，A和B存在依赖关系，假设A依赖B，可以A中require B的本地代码，这样在安装B的时候，npm就会通过指定的本地路径将B安装到A的node_modules中\n\n具体使用参考：[eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import/blob/001b8de7fb067167ee1d53252cff914e9b93464c/package.json#L59)\n\ndevDependencies和dependencies中都声明了`eslint-import-resolver-node`的依赖，但devDependencies中用的是本地代码，调试通过后再发布当前仓库和`eslint-import-resolver-node`到npm\n\n参考：https://github.com/timoxley/linklocal#about\n\n### npm t\n\nshort for `npm test`\n\n### npm.im\n\nhttps://npm.im/pure-ui\n\n### npm cdn\n\nhttps://unpkg.com/pure-ui/dist/\n\n### npm search\n\nhttps://npms.io/\n\n### scoped-packages\n\n@开头的npm包\n\n参考：[scoped-packages](https://docs.npmjs.com/getting-started/scoped-packages)\n\n### avoid installing devDependencies\n\n```bash\n$ npm install --production\n```\n\n### view package versions or tags\n\n```bash\n$ npm view «package-name» versions\n$ npm view «package-name» dist-tags\n```\n\n### publish with tag\n\n```bash\n$ npm publish --tag beta\n```\n\n默认会发布到latest的tag上，tag相当于是一个别名，作为一个特殊的发布通道，和chrome的canary、firefox的nightly是类似的\n\n注意：不要把tag名字用数字或v开头，可能会和semver版本号冲突\n\n参考：\nhttp://www.2ality.com/2015/12/npm-install-tag-version.html\nhttps://docs.npmjs.com/getting-started/using-tags\n\n### modify npm tag\n\n```bash\n$ npm dist-tag add packagename@1.1.0 latest\n```\n\n### clean npm cache\n\n```bash\n$ npm cache clean\n```\n\n### add package collaborators\n\n```bash\n$ npm owner add \u003cuser\u003e \u003cpackage name\u003e\n```\n\n### get global node_modules path\n\n```bash\n$ npm config get prefix\n```\n\n### register git subcommand with npm package\n\n```json\n{\n    \"git-jira\": \"bin/jira.js\"\n}\n```\n\n`git-jira` and `git jira` both work\n\n参考：https://github.com/commitizen/cz-cli\n\n### npm help scripts\n\n```bash\n$ npm help scripts\n```\n\n### transfer package ownership to others\n\n```bash\n$ npm owner add \u003cusername\u003e \u003cpackagename\u003e\n```\n\n### more npm tricks\n\n[...more npm tricks](https://gist.github.com/AvnerCohen/4051934)\n\n## yarn\n\n### install all dependencies\n\n```bash\n$ yarn\n```\n\n### install\n\n```bash\n$ yarn add \u003cpackageName\u003e\n```\n\n### uninstall\n\n```bash\n$ yarn remove \u003cpackageName\u003e\n```\n\n### add devDependencies\n\n```bash\n$ yarn add \u003cpackageName\u003e --dev\n```\n\n### add peerDependencies\n\n```bash\n$ yarn add \u003cpackageName\u003e --peer\n```\n\n### global install\n\n```bash\n$ yarn global add \u003cpackageName\u003e\n```\n\nnote: There are some issues with `global add` in windows OS\n\n### set registry\n\n```bash\n$ yarn config set registry https://registry.npm.taobao.org\n```\n\n### list all config\n\n```bash\n$ yarn config list\n```\n\n## Koa\n\n### get params\n\n```js\nctx.request.body // your POST params\nctx.params // URL params, like :id\nctx.query // params from querystring\n```\n\n## Node\n\n### clear command line console\n\n```js\nprocess.stdout.write( '\\x1bc' );\n```\n\n参考：[friendly-errors-webpack-plugin](https://github.com/geowarin/friendly-errors-webpack-plugin/blob/db5d5c9a48228e31ad429755f2304d9be57b96ba/src/output.js#L60)\n\n### run global package from command line -\u003e No such file or directory\n\nline-ending为CRLF，改成LF可以解决\n\n\u003e 可以在atom的core packages里面找到line-ending-selectoring，在setting里面修改新建文件时的默认换行符为LF\n\n其他可能的原因在这里有提到 https://github.com/nodejs/node-v0.x-archive/issues/3911#issuecomment-218380292\n\n### change working directory\n\n```js\nprocess.chdir( 'path/to/directory' );\n```\n\n### debug with chrome devtools\n\n```bash\nnode --inspect --debug-brk index.js\n```\n\nfor node v7+\n\n```bash\n$ node --inspect-brk index.js\n```\n\n参考：https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27\n\n### node REPL for multiline support\n\ntype \".editor\" in your node REPL for multiline support, and hit ^D to execute\n\n参考：https://twitter.com/atticoos/status/893496002933657600\n\n### delete require cache\n\n```js\ndelete require.cache[ require.resolve( '../../runners.json' ) ]\n```\n\n## Atom\n\n### solve conflicts with emmet-atom and autocomplete-plus\n\noverwrite enter in keymap.cson\n\n```\n'atom-text-editor:not(mini).autocomplete-active':\n    'enter': 'autocomplete-plus:confirm'\n```\n\n参考：https://github.com/emmetio/emmet-atom/issues/146#issuecomment-103475628\n\n### highlight according to file types\n\n```cson\ncore:\n   customFileTypes:\n      'text.html.basic': [\n        'rgl'\n      ]\n```\n\n参考：[Customizing Language Recognition](http://flight-manual.atom.io/using-atom/sections/basic-customization/#customizing-language-recognition)\n\n## Atom Package\n\n### auth\n\n```bash\n$ apm login\n```\n\n### release new version\n\n```bash\n$ apm publish patch/minor/major\n```\n\n### install your starred packages\n\n```bash\n$ apm stars --install\n```\n\n### install other user's starred packages\n\n```bash\n$ apm stars --user thedaniel --install\n```\n\n### get current file scope type\n\n```js\natom.workspace.getActiveTextEditor().getRootScopeDescriptor()\n```\n\n### how to find grammar scopes\n\nhttp://flight-manual.atom.io/behind-atom/sections/scoped-settings-scopes-and-scope-descriptors/\n\n## Package.json\n\n### dependencies version\n\n\u003e指定版本：比如1.2.2，遵循“大版本.次要版本.小版本”的格式规定，安装时只安装指定版本。\n\n\u003e波浪号（tilde）+指定版本：比如~1.2.2，表示安装1.2.x的最新版本（不低于1.2.2），但是不安装1.3.x，也就是说安装时不改变大版本号和次要版本号。\n\n\u003e插入号（caret）+指定版本：比如ˆ1.2.2，表示安装1.x.x的最新版本（不低于1.2.2），但是不安装2.x.x，也就是说安装时不改变大版本号。需要注意的是，如果大版本号为0，则插入号的行为与波浪号相同，这是因为此时处于开发阶段，即使是次要版本号变动，也可能带来程序的不兼容。\n\n\u003elatest：安装最新版本。\n\n\u003e 摘自[package.json文件](http://javascript.ruanyifeng.com/nodejs/packagejson.html#toc2)\n\n### prepublish\n\n```json\n{\n    \"scripts\": {\n        \"prepublish\": \"...\"\n    }\n}\n```\n\nexecute some commands before publishing to npm\n\n### \"gulp-babel\": \"babel/gulp-babel#d8c67b\"\n\n```json\n{\n    \"devDependencies\": {\n        \"gulp-babel\": \"babel/gulp-babel#d8c67b\"\n    }\n}\n```\n\nThis will pick a specific commit\n\n参考：https://github.com/babel/babel/pull/6056/files#r137702263\n\n## Webpack\n\n### dynamic require all modules from directory\n\n```js\nconst load = requireContext =\u003e {\n\treturn requireContext.keys().map(requireContext)\n}\n\nconst modules = load(require.context('./', true, /.js$/))\n```\n\n\u003e requireContext.keys()会返回当前上下文下的所有路径，requireContext本身是一个函数，可以当作require来用(基于某个上下文的)\n\n\u003e 参考：[webpack文档](https://webpack.github.io/docs/context.html#context-module-api)\n\n### make webpack output colorful when using webpack-dev-middleware\n\nAdd `colors: true`\n\n```js\nwebpackDevMiddleware( compiler, {\n\tstats: {\n\t\tcolors: true\n\t}\n} );\n```\n\n### hide extra info when bundling with webpack-dev-middleware\n\n```js\nwebpackDevMiddleware( compiler, {\n\tstats: {\n\t\tmodules: false,\n\t\tchildren: false,\n\t\tchunks: false,\n\t\tchunkModules: false,\n\t}\n} );\n```\n\n### webpack doesn't looking up for peerDependencies in parent node_modules when in soft-linked node_modules\n\ne.g. When using lerna\n\n```js\nresolve: {\n  // 由于软链接后peerDependencies不会主动查找上层node_modules，指定fallback\n  fallback: _.cwd( 'node_modules' ),\n},\n```\n\n## Babel\n\n### babel6 always export a default to exports.default\n\nworkaround: [babel-plugin-add-module-exports](https://github.com/59naga/babel-plugin-add-module-exports)\n\n参考：http://stackoverflow.com/questions/34736771/webpack-umd-library-return-object-default\n\n## Lerna\n\n### lerna init\n\n初始化一个monorepo\n\n### lerna bootstrap\n\npackages中的包不需要发布到npm，但是如果没有发布的话需要自己手动在package.json中添加类似^0.1.0的依赖\n\n## Command line\n\n### back to previous directory\n\n```bash\n$ cd -\n```\n\n## Git\n\n### push local folder to github\n\n```bash\n$ git init\n$ git add -A\n$ git commit -m \"init\"\n$ git remote add origin git@github.com:\u003cyour_username\u003e/\u003cyour_repo_name\u003e.git\n$ git push -u origin master\n```\n\n### push and set upstream\n\n```bash\n$ git push -u origin branchName\n```\n\n### checkout to previous branch\n\n```bash\n$ git checkout -\n```\n\n### make git case-sensitive\n\n```bash\n$ git config core.ignorecase false\n```\n\n### git pull -\u003e error: unable to resolve reference refs/remotes/origin/xxx\n\n```bash\nrm .git/refs/remotes/origin/xxx\ngit fetch\n```\n\nit works for me\n\n### show all global config\n\n```bash\n$ git config --global -l\n```\n\n### discard unstaged changes\n\n#### a specific file\n\n```bash\n$ git checkout path/to/file\n```\n\n#### all unstaged files\n\n```bash\n$ git checkout -- .\n```\n\n参考：https://stackoverflow.com/questions/52704/how-do-i-discard-unstaged-changes-in-git/52713#52713\n\n## GitHub\n\n### search in certain path in github repo\n\n```\n\u003ckeyword\u003e path:\u003cpath\u003e\n```\n\n### readme\n\n\u003ckbd\u003eCtrl\u003c/kbd\u003e + \u003ckbd\u003eC\u003c/kbd\u003e\n\n```diff\n- \"build\": \"react-scripts build\"\n+ \"build\": \"react-scripts build \u0026\u0026 react-snapshot\"\n```\n\n| foo | bar |\n| :---: | :---: |\n\n☑☐\n\n⚠️\n\n⇗\n\n⬡\n\n### badges\n\n[![](https://img.shields.io/badge/made%20with-%e2%9d%a4-ff69b4.svg?style=flat-square)]()\n\n```\n[![](https://img.shields.io/badge/made%20with-%e2%9d%a4-ff69b4.svg?style=flat-square)]()\n```\n\nfrom: https://github.com/vinta/pangu.js/\n\n[![license](https://img.shields.io/badge/license-MIT-000000.svg?style=flat-square)](LICENSE)\n\n\n```\n[![license](https://img.shields.io/badge/license-MIT-000000.svg?style=flat-square)](LICENSE)\n```\n\n### rawgit cdn\n\ne.g. https://cdn.rawgit.com/Marak/faker.js/master/examples/browser/index.html\n\n## Electron\n\n### prevent redirect when drop files into electron window\n\n```js\nwin.webContents.on('will-navigate', event =\u003e {\n\tevent.preventDefault();\n\treturn false;\n});\n```\n\n```js\ndocument.addEventListener('dragover', function( event ) {\n\tevent.preventDefault();\n\treturn false;\n}, false);\n\ndocument.addEventListener('drop', function( event ) {\n\tevent.preventDefault();\n\t// let files = event.dataTransfer.files;\n\treturn false;\n}, false);\n```\n\n参考：https://github.com/electron/electron/issues/5919\n\n### can't find module xxx after packaging\n\n打包前正常，打包后报`can't find module xxx`的错误，之前一次遇到是因为安装titlebar的时候没有保存到package.json的依赖列表中，重新用npm i titlebar -S安装，再打包，没有出现报错\n\n### launch at login\n\n\u003e electron added built-in support for launching at login using app.setLoginItemSettings. One drawback is that it only works for macOS and Windows at the moment, whereas the auto-launch npm package works on Linux too\n\n参考：https://github.com/muan/mojibar/issues/67\n\n### ready-to-show\n\n在ready-to-show触发后再显示主窗口，可以有更好的体验\n\n## JavaScript\n\n### const is block-scoped\n\nConstants are block-scoped, much like variables defined using the let statement\n\n参考：[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n\n### es6 解构 + 别名\n\n```js\nconst { types: t } = babel;\n```\n\n等价于\n\n```\nconst t = babel.types;\n```\n\n### Promise.race([]) returns a forever pending promise\n\nhttps://twitter.com/jdalton/status/790263748732661760\n\n### for ... in\n\nfor in 循环的顺序和书写的顺序有关\n比如遍历\n```js\n{\n\ta: 1,\n\tb: 1,\n\tc: 1\n}\n```\n和\n```js\n{\n\tc: 1,\n\tb: 1,\n\ta: 1\n}\n```\n的顺序是不一样的\n\n### use yield with an array in co\n\n```js\nconst [ rst0, rst1 ] = yield [ promise0, promise1 ];\n```\n\n### filter out falsy values\n\n```js\n// filter out falsy values\n[].filter(Boolean)\n```\n\n参考：https://github.com/babel/babel/blob/53ed4e5eb86902cf577e990bfe4f7d917a66ea65/packages/babel-preset-es2015/src/index.js#L72\n\n### comment\n\n```js\n/* ---------------- 8\u003c -------- 8\u003c ---------------- */\n```\n\nfrom [proselint](https://github.com/sapegin/proselint/blob/23227be2448518b6003902187ebb27db63d657cf/src/index.js#L32)\n\n```js\n// Backbone.sync\n// -------------\n```\n\nfrom [backbone](https://github.com/jashkenas/backbone/blob/3141352b83e78a41c524fb69c39219550a056e0d/backbone.js#L1469-L1470)\n\n```js\n// ===================== //\n// _nativeFunctionObject //\n// ===================== //\n```\n\nfrom [otto](https://github.com/robertkrimen/otto/blob/master/type_function.go#L28-L30)\n\n### Array.prototype.includes\n\n[ NaN ].indexOf( NaN ) === -1\n[ NaN ].includes( NaN ) === true\n\n### a.splice(i \u003e\u003e\u003e 0, 1) === if (i !== -1) a.splice(i, 1)\n\n因为-1 \u003e\u003e\u003e 0 === 0xFFFFFFFF, max possible array length\n所以上面两者是等价的\n\n参考：https://github.com/ai/nanoevents/blob/f445d5fe7beccdb5ae0c57858444fe9a8b7c38e7/index.js#L66\n\n### add font-family via js\n\n```js\nconst iconfont = new FontFace(fontFamily, 'url(' + uri + ')');\ndocument.fonts.add(iconfont);\n```\n\n参考：[rax-icon](https://github.com/alibaba/rax/blob/fd216de80df3910c7c0f4108d254d985e1b4dd79/packages/rax-icon/src/index.js#L33-L35)\n\n### 8 immutable arrays operations you should know\n\n![](https://i.loli.net/2017/12/12/5a2f9eb4c9749.png)\n\n参考：https://twitter.com/lukejacksonn/status/928244319760220160\n\n### 9 get language in browser\n\n```js\nnavigator.language // \"zh-CN\"\n```\n\n## JavaScript Snippets\n\n### how to slice arguments without leaking them\n\n\u003e https://gist.github.com/WebReflection/4327762cb87a8c634a29\n\n```js\n// Andrea Giammarchi, WTFPL\nfunction slice() {'use strict';\n  for (var\n    o = +this,                // offset\n    i = o,                    // start index\n    l = arguments.length,     // length\n    n = l - o,                // new length\n    a = Array(n \u003c 0 ? 0 : n); // new Array\n    i \u003c l; i++\n  ) a[i - o] = arguments[i];\n  return a;\n}\n\n/**\n * @example\n(function () {\n  slice.apply(0, arguments); // [1,2,3]\n  slice.apply(1, arguments); // [2,3]\n  slice.apply(6, arguments); // []\n}(1,2,3));\n */\n```\n\n### fast bind\n\n\u003e https://gist.github.com/WebReflection/40e68a4f603ef788121a\n\n```js\n(function (FunctionPrototype) {\n  'use strict';\n  var originalBind = FunctionPrototype.bind;\n  if (!originalBind.patched) {\n    Object.defineProperty(\n      FunctionPrototype,\n      'bind',\n      {\n        configurable: true,\n        value: function bind(context) {\n          var callback = this;\n          return arguments.length === 1 ?\n              function () { return callback.apply(context, arguments); } :\n              originalBind.apply(callback, arguments);\n        }\n      }\n    );\n    FunctionPrototype.bind.patched = true;\n  }\n}(Function.prototype));\n```\n\n### play sound from arraybuffer\n\n```js\nconst context = new AudioContext();\n\nfunction playSound( buffer ) {\n\tconst source = context.createBufferSource();\n\tsource.buffer = buffer;\n\tsource.connect( context.destination );\n\tsource.start( 0 );\n}\n\nfetch( `https://dict.youdao.com/dictvoice?type=2\u0026audio=word` )\n\t.then(response =\u003e response.arrayBuffer())\n\t.then(buffer =\u003e {\n\t\ttry {\n\t\t\tcontext.decodeAudioData(buffer, b =\u003e {\n\t\t\t\tplaySound( b );\n\t\t\t});\n\t\t} catch( e ) {\n\n\t\t}\n\t});\n```\n\n### escape regexp\n\n```js\nfunction escapeRegExp(string){\n\treturn string.replace(/([.*+?^=!:${}()|[\\]\\/\\\\])/g, \"\\\\$\u0026\"); //$\u0026表示被匹配的字符串\n}\n```\n\n比如这样一个字符串\n\n```\n~!@#$%^\u0026*()_+{}|:\"\u003c\u003e?[];',./-=！￥…（）—：“《》？【】、；‘，。·～＠＃％＆×＋｛｝｜”＼’－＝\n```\n\n转义其中需要转义的部分\n\n```js\nescapeRegExp(`~!@#$%^\u0026*()_+{}|:\"\u003c\u003e?[];',./-=！￥…（）—：“《》？【】、；‘，。·～＠＃％＆×＋｛｝｜”＼’－＝`)\n```\n\n结果\n\n```\n~\\!@#\\$%\\^\u0026\\*\\(\\)_\\+\\{\\}\\|\\:\"\u003c\u003e\\?\\[\\];',\\.\\/-\\=！￥…（）—：“《》？【】、；‘，。·～＠＃％＆×＋｛｝｜”＼’－＝\n```\n\n这样就能直接放到正则中使用了\n\n```js\n/^[~\\!@#\\$%\\^\u0026\\*\\(\\)_\\+\\{\\}\\|\\:\"\u003c\u003e\\?\\[\\];',\\.\\/-\\=！￥…（）—：“《》？【】、；‘，。·～＠＃％＆×＋｛｝｜”＼’－＝]+$/.test( '#' );\n```\n\n参考：[MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions)\n\n### log string in format\n\n```js\nconsole.log('new: %s, old: %s', new, old);\n```\n\n### neat way to chain promises\n\n```js\nconst ArrarOfFunctionsReturnPromise = [ ... ];\nArrarOfFunctionsReturnPromise.reduce( function ( total, current ) {\n    return total.then( current );\n}, Promise.resolve() ).then( ... );\n```\n\n### find function definition in Source panel in console\n\n```js\ninspect( fn )\n```\n\n### measure text in canvas context\n\n```js\nctx.measureText( 'text' )\n```\n\n### get network status\n\n```js\nnavigator.onLine\n```\n\n### network events\n\n```js\nwindow.addEventListener('online', whenOnline)\nwindow.addEventListener('offline', whenOffline)\n```\n\n## CSS Snippets\n\n### auto fit content width\n\n```css\n/* 宽度自适应内容 */\nwidth: -webkit-fit-content\n```\n\n### @supports\n\n```css\n@supports( display: grid ) {\n\t/* ... */\n}\n```\n\n### repeating-linear-gradient\n\n```css\nbackground-color: #eee;\nbackground-image: repeating-linear-gradient(-45deg,transparent,transparent 5px,rgba(255,255,255,.5) 5px,rgba(255,255,255,.5) 10px), repeating-linear-gradient(45deg,transparent,transparent 5px,rgba(255,255,255,.5) 5px,rgba(255,255,255,.5) 10px);\n```\n\n### grid-like\n\n```css\nbackground-color: rgba(0, 0, 0, 0.05);\nbackground-image: repeating-linear-gradient(0deg, transparent, transparent 7px, rgba(0, 0, 0, 0.2) 1px, transparent 8px), repeating-linear-gradient(90deg, transparent, transparent 7px, rgba(0, 0, 0, 0.2) 1px, transparent 8px);\nbackground-size: 8px 8px;\n```\n\n### text gradient\n\n```css\nbackground: -webkit-linear-gradient(left,#00c0f9, #4d8cff, #9f72ff);\n-webkit-background-clip: text;\n-webkit-text-fill-color: transparent;\n```\n\n参考：https://atomiks.github.io/tippyjs/\n\n## Others\n\n### Don’t write “flexible” modules\n\n\u003e Don’t write “flexible” modules. No matter how you plan, you’ll miss some future requirements. Write modules that are easy to delete.\n\n\u003e This is why composition is better than inheritance. Inheritance = trying to anticipate all future cases. Composition = replaceable units.\n\nhttps://twitter.com/dan_abramov/status/793124347573665796\n\n### lovely symbols\n\n˗ˏˋ text ˎˊ˗\n\n### try it on codepen\n\n\u003cimg src=\"http://blog.codepen.io/wp-content/uploads/2012/06/TryItOn-CodePen.png\" height=\"50\" /\u003e\n\n### Open in gitpod\n\n[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/firefox-devtools/profiler)\n\n### 暗中观察\n\n\u003e ┻┳|  \n\u003e ┳┻| _  \n\u003e ┻┳| •.•) 💬 *\"Tip: Use [pikapkg.com](https://www.pikapkg.com) to find modern, web-ready packages on npm :)\"*  \n\u003e ┳┻|⊂ﾉ     \n\u003e ┻┳|  \n\nfrom: https://github.com/pikapkg/web\n\n### 标题\n\n▍\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffengzilong%2Fcheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffengzilong%2Fcheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffengzilong%2Fcheatsheet/lists"}