Is there a way to bring in an NPM module without utilizing the keywords 'require' or 'import'?

After spending hours searching for a solution, I am still struggling with importing third-party libraries into my project that does not support 'import' or 'require'. It's frustrating to hit a roadblock like this, especially when working on a WordPress theme understrap.

Specifically, I need to include google-libphonenumber in my project, but I'm unsure how to do it without the familiar 'import' or 'require' commands I'm used to.

While some sources suggest using Browserify, my attempts to integrate it into my gulp workflow only resulted in more confusing errors.

package.json

"dependencies": {
    "@babel/preset-env": "^7.4.5",
    "bootstrap": "^4.3.1",
    "browser-sync": "^2.26.7",
    "css-element-queries": "^1.2.0",
    "del": "^4.1.0",
    "font-awesome": "^4.7.0",
    "gulp": "^3.0.0",
    "gulp-autoprefixer": "^6.0.0",
    "gulp-clean-css": "^4.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-ignore": "^2.0.2",
    "gulp-imagemin": "^5.0.3",
    "gulp-minify": "^3.1.0",
    "gulp-plumber": "^1.2.1",
    "gulp-rename": "^1.4.0",
    "gulp-replace": "^1.0.0",
    "gulp-rimraf": "^0.2.2",
    "gulp-sass": "^3.0.2",
    "gulp-sequence": "^1.0.0",
    "gulp-sourcemaps": "^2.6.5",
    "gulp-uglify": "^3.0.2",
    "gulp-watch": "^5.0.1",
    "javascript-detect-element-resize": "^0.5.3",
    "jquery": "^3.4.1",
    "libphonenumber-js": "^1.7.21",
    "run-sequence": "^2.2.1",
    "undescores-for-npm": "^1.0.0"
  }

import test

import { getPhoneCode } from 'libphonenumber-js';
$jq(function(){
  console.log(getPhoneCode('GB'));
}

This resulted in an error:

Uncaught SyntaxError: Unexpected token {

require test

var lib = require('libphonenumber-js');
$jq(function(){
  lib.isValidNumberForRegion('23123412', 'GB')
}

Which led to the following error:

Uncaught ReferenceError: require is not defined

Answer №1

Executing the script from unpkg

<script src="https://unpkg.com/google-libphonenumber@latest"></script>

Alternatively, you can run it from a local installation

<script src="node_modules/google-libphonenumber/dist/libphonenumber.js"></script>

Afterwards, you will be able to access the libphonenumber globally (in the window object)

Next, refer to the readme file but make some modifications:

// Acquire an instance of the `PhoneNumberUtil`.
//const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();

// Parse the number with the corresponding country code and maintain the raw input.
const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US');

// Display the country code of the phone number.
console.log(number.getCountryCode());
// => 1

// Display the national number of the phone.
console.log(number.getNationalNumber());
// => 2024561414

You will then see '2024561414' in your web browser console

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

NodeJS video streaming feature does not close the connection when the user disconnects or navigates to a different page

Currently, I'm in the process of developing a video streaming server using nodeJS with express. To monitor the progress status, I am utilizing the "request-progress" module. So far, everything pertaining to video streaming is working perfectly. Howev ...

"Use jQuery to target the first child element within a parent element that has a specific class

Is there a way to choose only the first child of a specific parent class with a certain class for the purpose of clone()? <div class="sector_order"> <div class="line_item_wrapper"> SELECT THIS DIV </div> <div class=" ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

How can I automatically update the content of a specific Div element when the page is loading using the Ajax load() function

This is the HTML code I have: <body onload="fun1()"> <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink" onclick="fun1()">Tab1</a></li> <li><a href="#" id="d_blink" onclick="f ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/ ...

Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'. In my express app setup, I have the following configuration: // Entry Point app.use("/", express.static(resolve(__di ...

Error: Module 'gulp-webserver' not located

Every time I try to run my node.js project using gulp, I encounter the error message "Error: Cannot find module 'gulp-webserver'". I have reinstalled the module using the following command but the issue still persists. $ npm install --save-dev g ...

Unable to submit form in Nextjs using react-bootstrap

Instructions To create a registration form, follow these steps: Fill out the form on the register page and then click submit. The react-bootstrap button will trigger the handleSubmit() function using onSubmit={}. Expected vs Actual Outcome I attempted va ...

What is the correct way to invoke a function from the reducer/actions within this specific scenario?

There seems to be an issue with the action/reducer I am attempting to call. It appears that the function is not being read correctly when called. The problem lies within the deleteWorkout function. I've attempted to use mapDispatchToProps and have al ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

The script for tracking cursor coordinates is incompatible with other JavaScript code

<html> <script language="javascript"> document.onmousemove=function(evt) { evt = (evt || event); document.getElementById('x').value = evt.clientX; document.getElementById('y').value = evt.clientY; document.ge ...

Encountered problem in React Native app creation: npm terminated with error code 1

Welcome to the expo initialization process with test111 project! Choose a template: expo-template-tabs. Using npm to install packages. You can pass --yarn to use Yarn instead. Extracting project files... Attempting to customize the project... Oh no, we h ...

Modify the CSS properties of the asp:AutoCompleteExtender using JavaScript

Is there a way to dynamically change the CompletionListItemCssClass attribute of an asp:AutoCompleteExtender using JavaScript every time the index of a combobox is changed? Here is the code snippet: ajaxtoolkit: <asp:AutoCompleteExtender ID="autocom" C ...

Discovering visible ID numbers on the screen

My content includes the following: <div id="sContainer"> <div class="message0" id="l0">Initial Content 111</div> <div class="message1" id="l1">Initial Content 222</div> <div class="message2" id="l2">Initial ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Getting hold of parameters passed through npm run-script

The command I execute is: npm run a_script --oki="odo" Is there a way to access the value of oki in my script? My intention is to use it like this: if(process.argv.oki === 'odo'). I attempted to do this: console.log(process.argv); However, i ...

Tips for implementing JWT in a Node.js-based proxy server:

I am a Node.js beginner with a newbie question. I'm not sure if this is the right place to ask, but I need ideas from this community. Here's what I'm trying to do: Server Configurations: Node.js - 4.0.0 Hapi.js - 10.0.0 Redis Scenario: ...

Issue with Node.js Express function not returning the variable fetched from fs.readFile operation

I am facing an issue with a function in my Node.js application that uses Express. function getMetaInfo(id){ var directory = 'files/' + id; var totalCount = 0; fs.readFile(__dirname + '/' + directory + '/myfile.json&ap ...