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

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...

What is the best approach to link an HTML document to a MySQL Workbench server utilizing JavaScript, Ajax, and PHP?

On my HTML page, users can enter the name of a movie and if it is found in the database, the name will be displayed. I am attempting to establish a connection to the MySQL Workbench Server using JavaScript, Ajax, and PHP. This is what I have implemented s ...

Utilize an array value as a parameter for getStaticProps within Next.js

Currently, I am fetching my Youtube playlist using a fetch request and utilizing getStaticProps(). However, I am encountering an issue where my playlist is dependent on the result of an array of objects. export async function getStaticProps(){ const MY_P ...

Purging information from JavaScript object

Looking for a way to remove just one piece of data from a JavaScript object in my React app. Here's the structure of the object: state = { data: [] } const contactData = { Datas: { name: "william", email: "<a href="/cdn-cgi/l/email-pr ...

The issue with mCustomScrollbar's "scrollTo" function not functioning properly has been detected within a single-page application

Although there are many similar questions out there, I have been unable to find a solution to my particular issue. In my single page application with metro style design, I am facing an issue where the scroll position does not reset back to its original pl ...

Tips for sending images as properties in an array of objects in React

I've been experimenting with various methods to display a background image underneath the "box" in styled components. How can I pass an image as a prop into the background image of the box with the image stored in the array of objects? I'm unsure ...

Icons in Semantic-UI: Facing Difficulty in Accessing ("CORS Request Not HTTP"

Here's an example I'm working on: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Understanding - Main</title> <link rel="stylesheet" type="text/css" href="../semantic/dist/semanti ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...

What are the security risks of evaluating user-supplied strings in web browser storage?

I'm in the final stages of developing a script that creates an API for performing storage operations across various web browser storage technologies. Currently, I am focusing on adding conditional retrieval and removal functionalities. These features ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

Encountering the error message "handleChange is not a function" when trying to select a date in Material UI

Encountering an error message 'handleChange is not a function' when selecting a specific date in the DatePicker component. The DatePicker component is nested within the Controller component of react-hook-form. The expected behavior is to display ...

Is it advisable to approve automatic pull requests initiated by dependabot for updating the yarn.lock file?

I've recently received some pull requests from "dependabot" in a JavaScript library I am working on, like the one found here. While I appreciate the effort to update dependencies to newer versions, it seems strange that each PR only updates the versi ...

Angular: Backend responds with a token which Angular then stores within double quotes

Following the BE response, this code snippet is what I have: $cookieStore.put('Auth-Token', user.authToken); However, when checking the cookies, I notice that it displays Auth-Token: %220996dcbe-63e6-4d99-bd17-d258e0cc177e%22 Upon logging it to t ...

Creating an input range element and its event handler dynamically within the ajaxStop function allows for real-time updates based on the

As a beginner in JavaScript development and Ajax, I am currently working on creating a webpage that utilizes Ajax to fetch data from a server. The data is then used to draw geoJSON features on a map using Leaflet. These feature sets need to be toggleable f ...

Enhance local rotation of objects in Three.js

I am working on creating a spaceship-like object with controls, and I have learned that I need to use quaternions to achieve this. To start, I am attempting to make a cube rotate to the left when the A key is pressed. Here is the code I have written for th ...

Thumbnail Option in the WordPress Media Uploader

Is it possible to add support for selecting image size (thumbnails) in the Media Library popup created using the wp.media() function in WordPress? I am currently using WordPress 4.5.2 and my code sample is as follows: wp.media.frames.selectFile=wp.media( ...

Utilizing AJAX to send RSS feeds to a Django view

I'm fairly new to using ajax. Here's the scenario I'm dealing with: I'm working on a side project that involves displaying news and scores for various sports. To achieve this, I'm utilizing rss feeds from different sources. In my D ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

Delaying http requests until cache is fully prepared without the need for constant checking

In a unique scenario I am facing, my http requests are caching intermediary results on the server. If the cache is not found, then another server is requested to build it. These requests are sent consecutively (in a loop) using AJAX to a Node Server, with ...

In JavaScript, the condition can function properly even without the "&&" logical operator, but if the "&&" is included, the condition does not operate

I need the error message to be shown if the character length in the #nameT id is less than 3 or greater than 20. When I use the && logical operator, it does not function correctly, as when the && is not present, it works perfectly when ex ...