【问题标题】:How to achieve inheritance in ES6 with "webpack module bundler"?如何使用“webpack module bundler”在 ES6 中实现继承?
【发布时间】:2016-03-13 19:17:35
【问题描述】:

在 ES6 类中无法实现继承,当使用带有 babel 的 webpack 模块捆绑器导入两个文件时

我的目录结构是这样的

webpack.config.js 看起来像

module.exports = {
  entry: "./entry.js",
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
  module: {
    loaders: [
    {
      loader: "babel-loader",
      // Only run `.js` and `.jsx` files through Babel
      test: /\.jsx?$/,
      // Options to configure babel with
      query: {
        presets: ['es2015'],
      }
    },
  ]
  }
};

Entry.js 看起来像

import './content.js';
import './content1.js';

content.js 看起来像

export class addition {
  constructor(){
    this.x = 10 ;
  }
}

content1.js 看起来像

class subtraction extends addition{
  constructor(){
    super();
    this.y = this.x - 5 ;
  }
}

var inst = new subtraction();
console.log(inst.x, inst.y)

使用 webpack 生成 bundle.js 并运行 index.html 后:出现类似错误

请帮我弄清楚,如何在 ES6 中使用 webpack 模块捆绑器实现继承。

【问题讨论】:

    标签: javascript ecmascript-6 webpack es6-module-loader


    【解决方案1】:

    每个模块都必须导入其所有依赖项:

    import {addition} from './content';
    
    class subtraction extends addition {
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2018-02-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多