How can I confine a non-UMD module that has been imported in Webpack and Typescript to just one file?

When working on a project that involves Typescript and Webpack, I want to make sure that global libraries, such as jQuery, are treated as UMD globals.

Currently, if I do not include import * as $ from 'jQuery' in a file where I am using $, webpack builds successfully but the script fails during runtime. On the other hand, omitting import * as _ from 'lodash' causes webpack to fail, as expected.

Take a look at the following files:

first.ts

import * as $ from "jquery";
import * as _ from "lodash";

import { second } from "./second";

$(() => {
    const message = _.identity("first.ts");
    $(".first").html(message);
    second.Test();
});

second.ts

//import * as $ from "jquery";
//import * as _ from "lodash";

export const second = {
    Test: () => {
        const message = _.identity("second.ts");
        $(".second").html(message);
    }
}

index.html

<html>
    <head>
        <script type="text/javascript" src="./bundle.js">
        </script>
    </head>
<body>
<div class="first"></div>
<div class="second"></div>
</body>
</html>

package.json

{
  "name": "webpack-typescript-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jquery": "^2.0.46",
    "@types/lodash": "^4.14.65",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.3",
    "webpack": "^2.6.1"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES5",
        "sourceMap": true,
        "module": "commonjs",
        "types": []
    },
    "include": [
        "./*.ts"
    ],
    "exclude": [
        "./node_modules"
    ]
}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './first.ts',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname)
    }
}

Is there a way to enforce the import statements in all .ts files?

Answer №1

Have you thought about implementing the externals option in your webpack configuration? It could be a useful tool for optimizing your project: https://webpack.js.org/configuration/externals/

It seems like it could align perfectly with your specific needs.

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

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

The issue arises when trying to call a JavaScript function that has not been properly

Initially, write code in resources/js/app.js file function button1Clicked(){ console.log('Button 1 is clicked'); } Next, include the following code in testing.blade.php file <!DOCTYPE html> <html> <head> <meta name="cs ...

Navigating with Angular and Express

Currently, my Angular project is configured with Express serving my index.html file. As the project progressed, I found the need for a landing page that requires some functionality from the index.html file, such as form input that triggers an API call. H ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

Tips for maintaining server session by tracking user activity on the browser using a simple ajax request to the server without relying on JQuery

In my website, the server session Timeout is set to 30 minutes. <system.web> <sessionState timeout="30" /> </system.web> However, if a user is actively engaging with the site by typing a long comment or selecting chec ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Leverage the TypeScript compiler's output from a .NET library within a Blazor application by referencing it

I am currently facing an issue with three different levels: Main Issue: I have developed a Blazor WebAssembly (WASM) application that requires JavaScript, but I prefer to use TypeScript. To address this, I have added a tsconfig file and the TypeScript cod ...

Switching Primary Menu Selection When Scrolling Through Various Menu Options

I need help with changing the active class of links on my single page scrolling website. I found some useful code snippets for smooth scrolling and updating the active class on scroll or click events: $(document).ready(function () { $(document).on(" ...

Unable to remove div element

Currently, I am working on writing a code for a webpage with specific functionalities. I need to display a button and an embedded YouTube video. When the user clicks on the video, they should be redirected to a different link (not YouTube) and the video sh ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

What is the best way to turn off default CSS styling in KendoUI?

I am facing an issue in my application where I am using global CSS definitions for "INPUT", "SELECT", and other elements. The problem arises when I try to incorporate KendoUI widgets, as they override my default CSS styles. For instance, my CSS code looks ...

Automate logging in and out of Gmail chat by programmatically simulating clicks on the span elements that represent the chat status in Gmail

When I'm at work, I prefer using Gmail's encrypted chat feature because it logs chats without saving anything to the hard drive. However, when I'm at home, I switch to Pidgin as logging into Gmail chat at home can lead to messages ending up ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

What code can I use to prompt clients to refresh JavaScript files automatically?

We are experiencing an issue where, even after pushing out updates with new JavaScript files, client browsers continue to use the cached version of the file and do not display the latest changes. While we can advise users to perform a ctrlF5 refresh during ...

Vercel Alert: (Azure) Missing OpenAI API key

After successfully implementing the openAI API in my Next.js application using the langchain library, everything worked flawlessly on localhost. However, upon deploying to Vercel (ProVersion), I encountered an error: Error: (Azure) OpenAI API key not fou ...

Using Angular to bind a click event to an element after it has been compiled

I am currently developing an application for students using Angular 5. In this application, users can access and view various documents. When a user enters a document, a set of tools, including a marker tool, are displayed. This marker tool allows users to ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...