Exploring Frontend Package Dependencies in Different Versions

As I develop the React frontend for a library package, I want to clearly display to users the specific version of the library being utilized. Apart from manual methods or relying on Node.js, I am unsure of alternative approaches to achieve this.

I am curious if there exists a method to transform the `package.json` file into a global JSON variable accessible to the frontend without relying on Node.js.

Answer №1

Using a Module Bundler

If you're utilizing a module bundler like webpack or rollup (which is recommended for npm packages), you can easily achieve this by...

commonjs

window.package = require('./package.json');

esm

import pkg from './package.json' assert {type: 'json'};

window.package = pkg;

The bundler will handle the import and bundle the json data into your output script, making it accessible in a browser via window.package.version.

If you are using Vite or rollup as your module bundler, to enable import assertions, make use of the

@babel/plugin-syntax-import-assertions
plugin. Here is an example with React:

import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ["@babel/plugin-syntax-import-assertions"],
      },
    }),
  ],
});

Without a Module Bundler

If you do not have a module bundler configured, you can still achieve this functionality by leveraging modules

index.html

<html>
  <head>
    <title>Import package.json</title>
  </head>
  <body>
    <script type="module">
      import pkg from "./package.json" assert { type: "json" };
      alert(pkg.version);
    </script>
  </body>
</html>

package.json

{
  "name": "js",
  "version": "0.0.0",
  "private": true,
  "dependencies": {}
}

Note: Trying to open index.html locally may result in a CORS error. It is necessary to serve the file. An easy way to serve this website on macOS is by using python..

python3 -m http.server 9000

Afterwards, access localhost:9000 in your browser to view your package version

https://i.sstatic.net/OhK3Q.png

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

What is the best way to consolidate all app dependencies into a single package?

Recently, I came across Cory House's ingenious solution for package management in Node.js during his informative presentation. In their project portfolio, House's team maintains a package called Fusion, which serves as a central repository for a ...

Control the movement of the mouse pointer using javascript

For my University presentation on click-jacking, I came across an intriguing example that I wanted to replicate but didn't know where to start. The whole concept seemed very complex to me. To get a better idea, please take a look at this video: https ...

Looking for an iframe that can adapt to varying content sizes and scale seamlessly with different screen dimensions?

I am new to advanced coding and currently working on my first responsive Wordpress site. I have a "Product Search" database/site that I'm trying to integrate into my website using an iFrame. I want the integration to look seamless without scroll bars ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

Tips for receiving accurate HTML content in an Ajax request

I have used an Ajax call to fetch data from a function that returns an entire HTML table. $.ajax({ url: "/admin/project/getProjectTrackedTimes", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('cont ...

Is it considered good practice to utilize Vue.js for managing global shared state and implementing for loops outside of components?

Just getting started with Vue.JS and experimenting with creating two lists of books (read and unread) from a shared object in the global data state. This is my approach - working demo (works like a charm! However, I'm wondering if this is considered ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

The issue persists with setState not functioning correctly and the checkboxes for filtering not registering as checked

I am currently in the process of developing a simple ecommerce platform which focuses on shoe shopping. Users will be able to search for shoes and apply filters based on brand and type. Here's where I stand with my progress: Clicking on filter check ...

What benefits come from installing modules such as socket.io/express globally?

Furthermore, I would like to explore the possibility of executing them from the /usr/local/lib directory instead of having to install these modules in the individual folders of each project I am currently managing. ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

"Enhance Your Online Shopping Experience with Woocommerce Ajax Filters and

I have a structure that looks like this: Company Google Apple Microsoft Material Wood Metal Plastic Essentially, Brand & Material are attributes in the Woocommerce system, while the rest are variables. I am currently working on implementing AJAX fi ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Shorten Text - React Native

I currently have a React Native application with a FlatList component. The logic I initially implemented was to display an Expand/Collapse arrow whenever the content at the 100th position in the list is not empty. However, I now realize that this approach ...

What are the steps for generating and implementing shared feature files in Cucumber?

I am currently utilizing Cucumber to define some tests for the project I am working on, but as the application grows larger, I find myself in need of a more efficient structure. project | feature_files | | app1.js | | app2.js | | app3.js ...

Efficiently removing a duplicated component in Vue: A step-by-step guide

I am trying to find a way to target and remove a component that I duplicated using the v-for directive in my multiple stopwatch application. Currently, I can only delete the last duplicated component, but I want the ability to remove any targeted component ...

Is there a way to showcase the JSON data within a nested array using VueJS?

Here is my Vue.js code: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id = window.location.href.split('=').pop(); ...

Passing a leading zero function as an argument in JavaScript

Is there a method for JavaScript to interpret leading zeros as arguments (with the primitive value as number)? I currently have this code: let noLeadingZero = (number) => { return number } console.log('noLeadingZero(00):', noLeadin ...

Is there a simple way to determine whether the operating system I am currently using is Windows or Mac when running npm scripts?

For a collaborative development project on a Mac environment, it is necessary to set chmod + x.usky /pre-commit for the projects. However, there may be individuals who intentionally do not set this in order to submit incorrect code to the repository I und ...

Error: Unable to publish - A previous publication already exists

npm ERR! publish Failed PUT 403 npm ERR! code E403 npm ERR! You cannot publish over the previously published versions: 1.1.1. : Despite using npm version patch, I am unable to publish my package. Here are the steps I follow: npm version patch update ...