thegreenwebfoundation / co2.js

An npm module for accessing the green web API, and estimating the carbon emissions from using digital services
Other
389 stars 49 forks source link

Switch to ES import syntax for tests #90

Closed mrchrisadams closed 2 years ago

mrchrisadams commented 2 years ago

This PR introduces the use of ES import syntax over the previous Commonjs based way of working with modules.

This is intended to pave the way for new creating multiple builds of co2.js, each of which are better suited for specific environments like:

Key changes

full extensions

Where we have been using require('./local/file'), because ES modules don't do the filename resolution when given an incomplete filename, we are explicit about the file we are importing from. For the most part this means a change like this:

// before assume this is a folder
const { thing } = require('./local') 

// after - we have to refer to the index file
import { thing } from './local/index.js'

splitting node out node specific and browser specific code

Where previously, we would have a single file like hosting.js, this is now split out into a default version aimed at browsers, and a separate hosting-node.js where we keep the node-specific APIs in their own files.

This should make it easier to import just the code you might need for a browser build, without needing polyfills, as the much of the functionality aimed at node-js wasn't relevant for browser users.

consistent use of the debug library for logging

We had a mix of console.log, and calls to log when using the debug library. Where we use the debug library, we use the import syntax instead like so

import debugFactory from "debug";
const log = debugFactory("tgwf:hostingAPI");

On the command line, this means we can turn on selective logging on nodejs, by setting DEBUG="tgwf:*" as an environment variable on the command line,.

In the browser we can do the same by setting localstorage.debug = "tgwf:*" to see all the logging that matches loggers with a name starting with tgwf .

introducing the use of esbuild as a single build / bundling tool

This also swaps out the use of babel, and earlier experiments with rollup, to just use esbuild for transpilation when running tests. This nets us a speed up, but also makes it easier to create runtime specific builds, and hybrid modules.

These are helpful for allowing us to support:

  1. commonjs based runtimes
  2. es module based runtimes
  3. more browsers that need to consume code as an iife

From a single code base and package.

updating eslint to support fetch with node and newer syntax

Instead of linting against an old versino of ecmascript, eslint now recognises the use of import and export.