0

I am trying to understand magic of frontend development and I still hit the wall while doing simple stuff.

I created and published simple npm package kosciej16-paczka

exports.printMsg = function() {
  console.log("This is a message from the demo package");
}

Now I want to use that anyhow. I created new package with npm init and wrote index.js

import printMsg from "kosciej16-paczka"

printMsg()

and som.html

<body>
    HA
    <script src=index.js>
    </script>
</body>

Then I read something that the browser cannot understand import syntax and I need to use different tool to translate the code. Ok, started to read about babel. Walk throught the tutorial and run npx babel src --out-dir lib with config provided there.

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1"
        },
        "useBuiltIns": "usage",
        "corejs": "3.6.5"
      }
    ]
  ]
}

Which created new index.js

"use strict";

var _kosciej16Paczka = _interopRequireDefault(require("kosciej16-paczka"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _kosciej16Paczka.default)();

So I tried to use that file in <script> tag but got an error about require is not defined.

That confused me totally - shouldn't babel functionality be creating code that browsers can run? What is the babel output for then?

I would be very gratefull for some up to date tutorial that explains things step by step and actually works,.

kosciej16
  • 6,294
  • 1
  • 18
  • 29
  • You need to show your babel config. Babel can compile to various targets. – morganney Oct 29 '22 at 14:34
  • Used one provided in the tutorial, updated the question – kosciej16 Oct 30 '22 at 18:44
  • You need either es modules with `script type="module"`, or a bundler like webpack. Babel doesn't transform the module loader used just converts from one version of ecmascript to another. Your question is mostly a duplicate of https://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel – morganney Oct 30 '22 at 22:19

0 Answers0