我尝试构建一个包装集合的模块失败了
我有类似的东西:
// topic: chess gaming
// file: src/core/Refs.js
const COLS = 'abcdefgh'.split('')
const ROWS = '12345678'.split('')
const ALL = new Map()
class Ref {
constructor (col, row) {
this.col = col
this.row = row
this.key = String(col + row)
}
// translate to ref to obtain another
// or null, if off-board
//
// ref.translate(0, 0) === ref (ok ?)
//
translate (dcol, drow) {
// compute something for dcol and drow
// ...
return ALL.get( COLS[colIdx] + ROWS[rowIdx] )
}
}
// the code which seems to not work propertly
for(let c of COLS) {
for(let r of ROWS) {
ALL.set(String(c + r), new Ref(c, r))
}
}
export default {
COLS, ROWS, ALL,
has (ref) {
return ALL.has(ref)
},
get (ref) {
return ALL.get(ref)
},
// trying to grant/warrant "immutability"
// for the "ALL" collection inside the module
keys() {
return [...ALL.keys()]
}
}
在我使用具有正确标志(dangerousForOf,..)和 objectAssign 的 Buble 编译模块后
然后我用 karma + jasmine 进行测试,第一个测试:
it ('should be 64-length array', function () {
expect (Refs.keys().length).toEqual(64)
})
将显示“期望 1 等于 64”,并且 Refs.ALL 的日志似乎显示一个空的 Map 尽管 Refs.COLS 和 Refs.ROWS 已正确初始化。
发生了什么以及如何解决它?
编辑:
@Bergi:当然,公开 Refs.ALL 会破坏不变性,而是出于调试目的
我不太确定如何捕获测试包输出,但看看 gulp+rollup 开发包,方法keys()行:
return [...ALL.keys()]
被替换为:
return [].concat(ALL.keys())
它生成一个包含 MapIterator 的 1 元素数组,这破坏了测试。放置类似:
return Array.from( ALL.keys() )
将解决该问题,但存在无法在旧版浏览器中正常工作的风险!
我已将代码推送到我的存储库上:https://github.com/hefeust/colorchess-v2
希望这可以帮助修复错误:如何在源代码中转换扩展(...)运算符以拥有包含正确的 Object.assign polyfill 的 bundle ?
最佳答案
Bublé does not support iterators ,这就是为什么它将具有扩展语法的数组文字转换为串联的原因。使用 Array.from 代替(无论如何,这更具描述性)。
return Array.from( ALL.keys() )
will fix the problem, but risks not to work properly in legacy browsers!
这应该不用担心 - 您正在使用 Map
对象及其返回迭代器的 keys()
方法,这在旧版浏览器中也不起作用。如果你打算支持它们,无论如何你都必须使用一个polyfill——而且你也会得到一个Array.from
的polyfill。
关于javascript - ES2015 模块初始化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757928/