Quantcast
Channel: Active questions tagged config - Stack Overflow
Viewing all articles
Browse latest Browse all 5049

How can classes be imported from a file generated with babel and webpack as is done with the normal ES6 files?

$
0
0

The truth is I had been struggling trying to understand, why I cannot import a class from a file that was previously generated with babel and webpack, and I want to show you my conclusion and also my confusion.

This is my structure folders

test-dist -test.js-public -index.html -main.js-src -test.js-package.json-webpack

So, If I do this

index.html

<!DOCTYPE html><html><body><script src="./main.js" type="module"></script></body></html>

test.js

export default class Person {    constructor() {        this.name = "Jon Doe";    }    getName() {        return this.name;    }}

main.js

import getName from "../src/test.js";let person = new Person();console.log(person.getName());

Ouput:

Jon Doe

So far everything works as expected using ES6 classes import and export

Then I use babel and webpack and I do the following like this.

package.json

{"name": "test","scripts": {"build": "webpack"  },"author": "shimozurdo","devDependencies": {"@babel/core": "^7.11.6","@babel/preset-env": "^7.11.5","webpack": "^4.44.1","webpack-cli": "^3.3.12",      "babel-loader": "^8.1.0"  }}

webpack.config

const path = require('path');module.exports = {    mode: 'development',    entry: {"test": './src/test.js',    },    output: {        path: path.resolve(__dirname, 'dist'),        filename: '[name].js',        library: 'testObj',        libraryTarget: 'umd',        umdNamedDefine: true    },    module: {        rules: [            {                test: /\.js$/,                exclude: /node_modules/,                loader: "babel-loader",                options: {"presets": ["@babel/preset-env"]                }            }        ]    }};

And then I use npm run build

index.html

<!DOCTYPE html><html><body><script src="../dist/test.js"></script><script src="./main.js"></script></body></html>

test.js

(function webpackUniversalModuleDefinition(root, factory) {    if(typeof exports === 'object'&& typeof module === 'object')        module.exports = factory();    else if(typeof define === 'function'&& define.amd)        define("testObj", [], factory);    else if(typeof exports === 'object')        exports["testObj"] = factory();    else        root["testObj"] = factory();})(window, function() {return /******/ (function(modules) { // webpackBootstrap/******/    // The module cache/******/    var installedModules = {};/******//******/    // The require function/******/    function __webpack_require__(moduleId) {/******//******/        // Check if module is in cache/******/        if(installedModules[moduleId]) {/******/            return installedModules[moduleId].exports;/******/        }/******/        // Create a new module (and put it into the cache)/******/        var module = installedModules[moduleId] = {/******/            i: moduleId,/******/            l: false,/******/            exports: {}/******/        };/******//******/        // Execute the module function/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);/******//******/        // Flag the module as loaded/******/        module.l = true;/******//******/        // Return the exports of the module/******/        return module.exports;/******/    }/******//******//******/    // expose the modules object (__webpack_modules__)/******/    __webpack_require__.m = modules;/******//******/    // expose the module cache/******/    __webpack_require__.c = installedModules;/******//******/    // define getter function for harmony exports/******/    __webpack_require__.d = function(exports, name, getter) {/******/        if(!__webpack_require__.o(exports, name)) {/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });/******/        }/******/    };/******//******/    // define __esModule on exports/******/    __webpack_require__.r = function(exports) {/******/        if(typeof Symbol !== 'undefined'&& Symbol.toStringTag) {/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });/******/        }/******/        Object.defineProperty(exports, '__esModule', { value: true });/******/    };/******//******/    // create a fake namespace object/******/    // mode & 1: value is a module id, require it/******/    // mode & 2: merge all properties of value into the ns/******/    // mode & 4: return value when already ns object/******/    // mode & 8|1: behave like require/******/    __webpack_require__.t = function(value, mode) {/******/        if(mode & 1) value = __webpack_require__(value);/******/        if(mode & 8) return value;/******/        if((mode & 4) && typeof value === 'object'&& value && value.__esModule) return value;/******/        var ns = Object.create(null);/******/        __webpack_require__.r(ns);/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));/******/        return ns;/******/    };/******//******/    // getDefaultExport function for compatibility with non-harmony modules/******/    __webpack_require__.n = function(module) {/******/        var getter = module && module.__esModule ?/******/            function getDefault() { return module['default']; } :/******/            function getModuleExports() { return module; };/******/        __webpack_require__.d(getter, 'a', getter);/******/        return getter;/******/    };/******//******/    // Object.prototype.hasOwnProperty.call/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };/******//******/    // __webpack_public_path__/******/    __webpack_require__.p = "";/******//******//******/    // Load entry module and return exports/******/    return __webpack_require__(__webpack_require__.s = "./src/test.js");/******/ })/************************************************************************//******/ ({/***/ "./src/test.js":/*!*********************!*\  !*** ./src/test.js ***!  \*********************//*! exports provided: default *//***/ (function(module, __webpack_exports__, __webpack_require__) {"use strict";eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Person; });\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar Person = /*#__PURE__*/function () {\n  function Person() {\n    _classCallCheck(this, Person);\n\n    this.name = \"Jon Doe\";\n  }\n\n  _createClass(Person, [{\n    key: \"getName\",\n    value: function getName() {\n      return this.name;\n    }\n  }]);\n\n  return Person;\n}();\n\n\n\n//# sourceURL=webpack://testObj/./src/test.js?");/***/ })/******/ });});

main.js

let person = new testObj.default;console.log(person.getName());

Ouput:

Jon Doe

Now, you can see I got the same result, but doing it like this

let person = new testObj.default;

This is my first problem, Is there something wrong with my babel/webpack configuration?

In the console looks like this

enter image description here

I am confused, if I tried to do it with an import I also get an error

index.html

<body>       <script src="./main.js" type="module"></script></body>

main.js

import Person from "../dist/test.js";console.log(Person);

enter image description here

I have not completely understood these concepts, but what confused me even a little more, was for example that in Phaser 3 I can easily import a class from the dist folder (installed via npm) like this import phaser from 'phaser', which was also generated with webpack and it works perfectly. What is missing from my configuration to be able to work with the imports of ES6?

I did the most basic example of this conclusion and confusion. Could someone help me?

Thanks in advance.


Viewing all articles
Browse latest Browse all 5049

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>