我有以下代码...
// 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不是构造函数
我应该如何导入呢?
答案 0 :(得分:0)
这有效...
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();
})()