【问题标题】:How do I instantiate a new Class after compiling to es5 using babel?使用 babel 编译到 es5 后如何实例化一个新类?
【发布时间】:2019-11-06 18:58:33
【问题描述】:

我有以下代码...

// index.mjs

class DoSomething{
    constructor(){
        console.log("Constructing");
    }
    doSomethingElse(){
        console.log("Something else");
    }
}

export { DoSomething }

它使用以下 webpack 规则编译...

  rules: [
      {
          test: /\.mjs$/,
          exclude: /(node_modules|bower_components)/,
          use: {
              loader: 'babel-loader',
              options: {
                  presets: ['@babel/preset-env']
              }
          }
      }
  ]

这会产生...

 //dist/sce.cjs
...
var DoSomething =
/*#__PURE__*/
function () {
  function DoSomething() {
    _classCallCheck(this, DoSomething);
    console.log("Constructing");
  }

  _createClass(DoSomething, [{
    key: "doSomethingElse",
    value: function doSomethingElse() {
      console.log("Something else");
    }
  }]);
  return DoSomething;
}();

但是当我尝试在这样的 CJS 脚本中实例化它时......

var lib = require("../dist/sce.cjs");
(function(){
    var instance = new lib.DoSomething();
    instance.doSomethingelse();
})()

我明白了

TypeError: lib.DoSomething 不是构造函数

我应该如何导入这个?

【问题讨论】:

    标签: webpack babeljs commonjs


    【解决方案1】:

    这行得通...

    const path = require('path');
    module.exports = {
      entry: path.resolve(__dirname, 'src/index.mjs'),
      output: {
          filename: 'sce.cjs',
          libraryTarget: 'commonjs'
      },
      module: {
          rules: [
              {
                  test: /\.mjs$/,
                  exclude: /(node_modules|bower_components)/,
                  use: {
                      loader: 'babel-loader',
                      options: {
                          presets: ['@babel/preset-env']
                      }
                  }
              }
          ]
      }
    }
    ...
    var DoSomething = require("../dist/sce.cjs").DoSomething;
    (function(){
        var instance = new DoSomething();
        instance.doSomethingElse();
    })()
    

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 2017-05-30
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多