[我在简化并找到各种答案后重写了问题。下面的Bergi有用的评论是指旧版本。]
Webpack似乎弄乱了扩展Array的类的对象。我认为这应该有效,并且它在节点和jsfiddle中都有效:https://jsfiddle.net/sigfried/n2pab49q/2/
"use strict";
class ThingArray extends Array {
constructor(data, parentThing) {
super(data);
console.log(`sending a [${this.constructor.toString().replace(/.\n[\w\W]*$/,'')}] to thing.method`);
debugger; // in browser console, type this.constructor, it shows
// ThingArray, but the console.log above shows Array
test(this);
}
}
function test(ta) {
console.log(`I'm expecting a ThingArray, and what I'm getting is a [${ta.constructor.toString().replace(/.\n[\w\W]*$/,'')}]`);
console.log(`Is it a ThingArray? The answer is ${!!(ta instanceof ThingArray)}`);
}
let twothings = new ThingArray(['baz',42]);
console.log(twothings);
if (typeof window !== "undefined") {
var div = document.getElementById('example');
div.innerHTML = twothings;
}
以前,代码和我对问题的理解要复杂得多。 我无法弄清楚我做错了什么。 Bergi鼓励我简化它,它看起来像一个webpack错误,根据我在下面添加的答案。但是为了防止我使用webpack错误,我将包含我的webpack.conf.js和package.json
var webpack = require('webpack');
module.exports = {
entry: [
'./index.js',
],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
]
},
};
{
"name": "array-extend-bug",
"version": "0.0.1",
"description": "problem with webpack handling array extensions",
"main": "index.js",
"scripts": {
"build": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git@gist.github.com:5c96b880d7986776e541.git"
},
"keywords": [
"webpack",
"es6",
"bug"
],
"author": "Sigfried Gold",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"babel": "^6.3.26",
"babel-core": "^6.0.12",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.12",
"babel-preset-stage-0": "^6.3.13",
"webpack": "^1.12.10",
"webpack-dev-server": "^1.14.1"
}
}
答案 0 :(得分:3)
扩展本地类型(如Array
)的能力是ES6的全新功能,只能使用真正的ES6类语法。因为它只能使用真正的ES6类,所以它也是不可转移的。
它在Node中工作,因为你的V8版本支持本机类,并且它在Webpack中不起作用,因为没有符合规范的方法使它在ES5中工作。
如果你真的想尝试入侵它,你可以使用transform-builtin-extend
这样的东西,但我真的不推荐它,因为你会遇到麻烦。如果您需要代码在新旧环境中一致地工作,最好不要将内置构造函数子类化。
答案 1 :(得分:1)
loganfsmyth是对的,我猜他自写作以来就欢迎我远离https://www.npmjs.com/package/babel-plugin-transform-builtin-extend。在巴贝尔松弛的通道上,他帮助我弄清楚如何让它工作,它完全解决了这个问题。这是我的新webpack.conf.js。除了babel-plugin-transform-builtin-extend之外,我还必须添加babel-polyfill。
{{1}}
这个要点通过webpack运行问题中的示例代码:https://gist.github.com/Sigfried/5c96b880d7986776e541。取出polyfill和transform-builtin-extend,它将在浏览器中再次启动失败,但不会在节点中失败。