I am trying to set up webpack in our javascript project and we want to write new javascript es6 classes, bundle them via webpack and then reuse the packages. I set up a simple example where i define a TestClass, which gets picked up and bundled by webpack, which i then use to import it in a second javascript file.
TestClass.js
:
class TestClass {
constructor() {
console.log("constructor called");
}
}
export default TestClass;
init.js
:
import TestClass from "./TestClass.js";
webpack.config.js
:
const path = require('path');
module.exports = {
mode: 'development',
watch: true,
entry: './init.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, '../WebContent/scripts/dist')
}
};
snippet from generated main.js
:
/***/ "./TestClass.js":
/*!**********************!*\
!*** ./TestClass.js ***!
\**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\nclass TestClass {\n constructor() {\n console.log(\"constructor called\");\n }\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TestClass);\n\n//# sourceURL=webpack://test/./TestClass.js?");
test.js
(where i want to use the TestClass):
import TestClass from './scripts/dist/main.js';
const test = new TestClass();
test.html
:
<!DOCTYPE html>
<html>
<head>
<script type="module" src="test.js"></script>
</head>
<body>
</body>
</html>
The webpack process seems to work fine but when executing test.js in my webapp i get the error
Uncaught SyntaxError SyntaxError: The requested module './scripts/dist/main.js' does not provide an export named 'default'
However when i import TestClass directly from TestClass.js it works like expected, so it cannot be problem about the class itself. Searching tutorials or asking chat gpt didn't bring my anywhere. Why does this not work?
TestClass.js
andinit.js
into a new, "down-piled"-to-ES5 file namedmain.js
, and then trying to ES6-importTestClass
from the ES5 result intotest.js
?