pimterry / loglevel

:ledger: Minimal lightweight logging for JavaScript, adding reliable log level methods to wrap any available console.log methods
MIT License
2.61k stars 157 forks source link

Alternative importing in browser as an ECMA module #153

Closed eouia closed 4 years ago

eouia commented 4 years ago

Thanks for your great job. I'm not sure this is a usual way to use this module in a browser, however, I want you to consider this.

WHAT I WANTED

I have an ECMA module js that is working on the browser, that module needs to import your loglevel. But don't want to load it explicitly by <script>. Because myModule will be loaded by the condition of the client.

[myConditionalModule.js]
import '/_/node_modules/loglevel/dist/loglevel.js' // served URL on my webserver
// or
import log from '/_/node_modules/loglevel/dist/loglevel.js'
// or
import * as log from '/_/node_modules/loglevel/dist/loglevel.js'
// or
import { log } form ....

log.warn('test') 

But every trial was failed.

In my Server part, it works nicely as importing ECMA scripts. I want to use this by the same way.

WHAT I TRIED

So, I tried some modification. https://github.com/pimterry/loglevel/blob/3bb1a53e9f927fd00b56461d90714f8ddee0595b/dist/loglevel.js#L8-L10

[loglevel.js]
} else {
    if (window) {
      window.log = definition()
    } else {
      root.log = definition()
    }
  }
[myConditionalModule.js]
import '/_/node_modules/loglevel/dist/loglevel.js' // served URL on my webserver
log.warn('test')

This works. Probably My original wanting was importing module as ECMA module locally. This is not fit perfectly. but anyhow I can use log.warn.

I don't know this is a proper way to use ECMA modules on the browser, Or I wish you provide separate mjs distro. I'm not experienced at Typescript or Grunt, so I cannot make a PR for you. sorry.

pimterry commented 4 years ago

I'm open to this, but I'm not sure how to do it either! I'm not familiar with the standards for using ESM directly (as opposed to using a bundler or compiler). If you or anybody else manages to put together a PR though, I'd be very interested.

In the meantime, if you're really keen to us ESM natively in the browser, I'd suggest using skypack, which acts as a CDN that transforms npm modules to ESM. This seems to work nicely:

import log from "https://cdn.skypack.dev/loglevel";
eouia commented 4 years ago

Thanks for the suggestion. Unfortunately, my project is something like standalone KIOSK which might have no internet connection. That's why served as a URL on the local webserver. But I'll try your suggestion on my other projects.

Anyway, I'm not familiar with the standards for using ESM directly without bundler, too. This project is somewhat annoying for me, due to;

I'll research more and tell you the result. Thanks again.