前端一万五 - 成长篇
私塾学者 2019-12-11
踩坑
knowledge
日常踩坑记录篇,记录项目中遇到的一些小知识点
# Javascript/TypeScript
# 循环和async的奇妙组合
const list = [1, 2, 3]
async function foo() {
return false
}
const data = list.every(async () => {
console.log('start')
const result = await foo()
console.log('end')
return result
})
console.log('JSLog: data', data) // ?
如果想连续执行await调用,请使用for循环(或任何没有回调的循环),推荐for-of替代
# 循环引用
// a.js
const b = require('./b')
b.getB()
const getA = () => {
console.log('getA')
}
module.exports = {
getA
}
// b.js
const a = require('./a')
a.getA()
const getB = () => {
console.log('getB')
}
module.exports = {
getB
}
a
模块和b
模块之间互相引用调用函数,将导致异常
# 判断数据类型的封装
const TYPES = [
'Boolean',
'Number',
'String',
'Function',
'Array',
'Date',
'RegExp',
'Object',
'Error'
]
export default TYPES.reduce((acc, item) => {
acc[`is${item}`] = obj => {
return Object.prototype.toString.call(obj) === `[object ${item}]`
}
return acc
}, {})
# promisify.js
export default api => {
return (options, ...params) => {
return new Promise((resolve, reject) => {
api(Object.assign({}, options, { success: resolve, fail: reject }), ...params)
})
}
}
# Tool
# Electron install fail
# v7
code ~/.npmrc
# npm config set ELECTRON_MIRROR=https://cdn.npm.taobao.org/dist/electron/
electron_mirror=https://cdn.npm.taobao.org/dist/electron/
electron_custom_dir=7.1.9
# v7 ↓
electron_mirror=https://npm.taobao.org/mirrors/electron/
# electron-vue init 缓慢
cd ~/Code
git clone https://gitee.com/mirrors/electron-vue.git #国内镜像
vue init ~/Code/electron-vue project-name
# electron-vue HtmlWebpackPlugin
error: Webpack ReferenceError: process is not defined
// .electron-vue/webpack.web.config.js
// .electron-vue/webpack.renderer.config.js
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
templateParameters(compilation, assets, options) {
return {
compilation: compilation,
webpack: compilation.getStats().toJson(),
webpackConfig: compilation.options,
htmlWebpackPlugin: {
files: assets,
options: options
},
process,
};
},
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
nodeModules: process.env.NODE_ENV !== 'production' ? path.resolve(__dirname, '../node_modules') : false
}),
# electron在mac电脑上复制粘贴全选失效
注意globalShortcut注册之后会覆盖其他的快捷键,所以blur的时候取消快捷键
app.on('browser-window-focus', () => {
if (!mainWindow) return
if (process.platform === 'darwin') {
let contents = mainWindow.webContents
globalShortcut.register('CommandOrControl+C', () => {
contents.copy()
})
globalShortcut.register('CommandOrControl+V', () => {
contents.paste()
})
globalShortcut.register('CommandOrControl+X', () => {
contents.cut()
})
globalShortcut.register('CommandOrControl+A', () => {
contents.selectAll()
})
}
})
app.on('browser-window-blur', () => {
globalShortcut.unregisterAll()
})