Utilizing Snowpack to implement private class methods in JavaScript

In my front-end development, I utilize private JavaScript class methods and Snowpack for my workflow.

Unfortunately, I've encountered an issue with Snowpack (as of v2.15.0-pre.5) not supporting private class methods. When trying to build using snowpack build, the following code fails:

export class TestClass {
  #test() {
    console.log("testing...");
  }

  test() {
    this.#test();
  }
}

To reproduce the issue, you can visit the repository here. After cloning, run:

npm install
npm run build

I have reported this issue to Snowpack, but it seems that the problem lies in its integration with Rollup and is not currently a priority for fixing.

To address this, it appears that we need:

  • a custom Rollup plugin for Snowpack.
  • this plugin should utilize acornInjectPlugins to inject acorn-private-methods.

I am seeking assistance or example of how to implement this before delving deep into learning the Rollup ecosystem. Are there any alternative solutions available?

For now, due to time constraints, I have resorted back to using _methodName instead of #methodName. However, I do plan on contributing a fix once time permits.

Answer №1

Snowpack Extension: snowpack-ext-acorn-enhancement

Building upon the foundation set by @noseratio, I have introduced a new Snowpack extension named snowpack-ext-acorn-enhancement. This extension injects necessary Acorn plugins into Rollup's internal setup.

You can find the extension here:


Illustration

Installation Procedure

Get the extension and the required Acorn plugin(s) (such as acorn-stage3) added to your project as development dependencies, following these steps:

Instructions:

  • npm:
    npm install --save-dev snowpack-ext-acorn-enhancement acorn-stage3
    
  • Yarn:
    yarn add --dev snowpack-ext-acorn-enhancement acorn-stage3
    

Customizing Snowpack

Set up your project's Snowpack configuration with snowpack-ext-acorn-enhancement and the relevant Acorn plugins:

{
  ...
  "plugins": [
    [
      "snowpack-ext-acorn-enhancement",
      {
        "plugins": [
          "acorn-stage3"
        ]
      }
    ]
  ],
  ...
}

Answer №2

I have solved the problem by utilizing Rollup.js options hook and the acorn plugin called acorn-stage3. You can find the repository here.

You can also use acorn-private-methods if you only need private methods.

  • To implement this, I created a custom Rollup.js plugin which I named @noseratio/rollup-acorn-conf:
"use strict";

module.exports = function plugin(hostOpts = {}) {
  return { 
    name: 'rollup-acorn-conf',

    options: rollupOpts => { 
      console.log("Enabling 'acorn-stage3'...");
      rollupOpts.acorn = rollupOpts.acorn ?? {};
      rollupOpts.acorn.ecmaVersion = 2020;
      rollupOpts.acornInjectPlugins = rollupOpts.acornInjectPlugins ?? [];
      rollupOpts.acornInjectPlugins.push(require('acorn-stage3'));
      return rollupOpts;
    }
  };
};

The package.json file for this plugin is as follows:

{
  "name": "@noseratio/rollup-acorn-conf",
  "version": "0.1.1",
  "description": "Enable ES2020 features (Stage 3) for Rollup.js",
  "homepage": "https://github.com/noseratio/snowpack-discussions-1209",
  "main": "index.js",
  "scripts": {},
  "devDependencies": {
    "acorn-stage3": "^4.0.0"
  }
}
  • In the snowpack.config.js file:
  installOptions: {
    rollup: { 
      plugins: [require('@noseratio/rollup-acorn-conf')()]
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After re ...

Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. Ho ...

Sort through data based on specific data fields upon the button click event using JSON and Vue.js

Is there a way to use JSON files in Vue.js to filter data based on category when a button is pressed? I have objects with categories inside the data. portfolio-v1.json { "data":[ { "image_path":"static/products/DEL ...

Obtaining the Immediate ID of a Widget using JQuery

I currently have the following setup: <div id="dualList"></div> I created a plugin but stripped it down for testing purposes. I am encountering difficulties with the plugin not displaying the ID of the div. <script> (function($) { ...

When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects." In the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Encountering an issue while attempting to locate an already existing product in the localStorage using JavaScript

I'm currently working on incorporating a cart system using localStorage and have provided the codes below. Can someone help me understand how to accomplish this? const data = { description: "Cum sociis natoque", mediaUrl: "/prod ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

I am attempting to develop a basic express application, but it doesn't appear to be functioning as expected

I am currently working on developing a straightforward express application. However, I am facing network errors when trying to access it through my browser at localhost:3000 while the application is running in the console. The root cause of this issue elud ...

AngularJS - Create Alert Pop-Up for Missing Input Fields

I've been struggling to set up my app so that it displays an alert when the user attempts to submit a form with an empty input box. Despite having a confirmation popup working in another part of the application, I can't seem to figure out why thi ...

Looking to obtain the coordinates of a draggable element?

After dragging a div around the page and submitting a form, I would like to capture its location on the page so it can render in that same spot when the page reloads. My current question is how can I capture the coordinates or location of the div after it ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

Need to send emails to two separate users? Look no further than Resend.com for a quick and

I am currently utilizing resend.com to send an email containing different variables to two distinct users. import type { NextApiRequest, NextApiResponse } from "next"; import { EmailTemplate } from "../../components/emails/EmailTemplate" ...

Sending POST data to a PHP file without the use of jQuery results in AJAX malfunction

I have been struggling to make an ajax alert layer work with a POST method for the past few days, and I cannot figure out why it is not functioning. I have successfully used the same code structure to send form data through ajax using POST on other admin p ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Showing a div with a smooth fade-in effect while switching its display property to inline using jQuery

Currently, I am working on a project that involves implementing a "side pop up". To ensure it doesn't flicker like it does with jQuery's "hide()" method, I want to start by setting the display property to none using CSS. My main question is: - Ho ...