我有一个如下定义的JavaScript模块:
const getQueryParameters = function* (obj, prefix) {
for (const [k1, v1] of Object.entries(obj)) {
const name = prefix === undefined || prefix === null ? k1 : `${prefix}.${k1}`;
if (typeof v1 === 'object') {
for (const [k2, v2] of getQueryParameters(v1, name)) {
yield [k2, v2];
}
}
else {
yield [name, v1];
}
}
};
module.exports = getQueryParameters;
在vue SFC中,我将其导入如下:
import 'babel-polyfill';
const getQueryParameters = require('../../modules/get-query-parameters.js');
我试图按如下方式称呼它:
const myObject = {
'foo': 42,
'bar': {
'baz': 'bof'
}
};
const params = {};
for (const [k, v] of getQueryParameters(myObject, null)) {
params[k] = v;
}
最后,我使用.babelrc
将其与webpack和babel进行如下转换:
{
"presets": [
[
"env",
{
"targets": {
"browsers": [
"last 2 versions",
"IE >= 11"
]
}
}
]
]
}
该过程可以按预期从节点运行(不进行编译),但是尝试在浏览器中运行时,出现以下错误:
vue.esm.js?a026:1741 TypeError: Cannot convert undefined or null to object
at Function.entries (<anonymous>)
at getQueryParameters$ (get-query-parameters.js?5f2b:64)
at tryCatch (runtime.js?f3a2:65)
at Generator.invoke [as _invoke] (runtime.js?f3a2:303)
at Generator.prototype.(anonymous function) [as next] (webpack-internal:///./node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:117:21)
at getQueryParameters$ (get-query-parameters.js?5f2b:63)
at tryCatch (runtime.js?f3a2:65)
at Generator.invoke [as _invoke] (runtime.js?f3a2:303)
at Generator.prototype.(anonymous function) [as next] (webpack-internal:///./node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:117:21)
at getQueryParameters$ (get-query-parameters.js?5f2b:63)
我想象我的babel配置不完整,但是看着错误,正确的babel插件(regenerator-runtime
)被调用了,正如我最初期望的那样。有人知道我在想什么吗?