thegreenwebfoundation / co2.js

An npm module for accessing the green web API, and estimating the carbon emissions from using digital services
https://developers.thegreenwebfoundation.org/
Other
417 stars 54 forks source link

Emissions can't easily be calculated in frontend framework #27

Closed ada-ada-ada-art closed 3 years ago

ada-ada-ada-art commented 4 years ago

Issue

When we worked on the Low Impact Website, we struggled a while with getting emissions calculations working on the frontend.

The issue mainly seemed to be that fs is not available in browsers, yet co2.js attempts to use it when following the instructions in the README.

Solution

There are a couple ways of getting around this. Two suggestions are:

  1. Simple version could be to provide instructions for using it on the frontend in the README (see further down)
  2. Make a check in the code for whether fs exists or not

Suggested README update

We got around it by simply importing the CO2 object directly from node_modules. So something like:

const CO2 = require('node_modules/@tgwf/co2/src/co2.js')
const bytesSent = (1024 * 1024 * 1024)
const co2Emission = new CO2();
estimatedCO2 = co2Emission.perByte(bytesSent)

Sidenote

To fetch the amount of bytes used on the page, we used the new Performance API. Specifically the transferSize of performance.getEntriesByType('resource').

It might be interesting to include that information in a README.

mrchrisadams commented 4 years ago

Hah, I had no idea anyone was actually using this, you've made my day @jepster-dk :)

I won't be able to get to this weekend, but I totally agree with the README update.

FWIW, in the later grid-intensity module I've worked on with some other cats, there's an approach that might work here.

Over there, we're using rollup to make browser specific builds, to account for node and browsers having different objects available to them. you can see in the config here, but also in the src directory with the browser specific bundle:

https://github.com/thegreenwebfoundation/grid-intensity/blob/main/rollup.config.js#L21

I've taken a different approach and gone through the faff of trying to learn rollup to make a tiny module you can bundle in a browser,and abstract away the differences. that way there's a browser specific build you can import in preferred toolchain.

Would you be okay with making a PR for the README changes in the interrim?

ada-ada-ada-art commented 4 years ago

I'm glad to hear! Love to make Fridays even better 🍻

I hadn't heard of the grid-intensity project, so thanks for sharing! We've actually used the same idea on our Low Impact Website, where we adapt the site to the carbon intensity. However we were under the same restriction of only being able to get UK data, since we used the carbonintensity.org.uk API.

I'm in talks with the ElectricityMap guys about some future stuff for us on this though.

In the meantime, I'll gladly add a PR for the README!