Issues with Webpack and TypeScript CommonsChunkPlugin functionality not functioning as expected

Despite following various tutorials on setting up CommonsChunkPlugin, I am unable to get it to work. I have also gone through the existing posts related to this issue without any success.

In my project, I have three TypeScript files that require the same libraries (fancybox, moment, and pikaday) using ES module syntax:

import * as fancybox from 'fancybox';
import * as moment from 'moment';
import * as pikaday from 'pikaday';

My tsconfig.json is configured to output ES6 syntax and modules:

{
    "compileOnSave": true,
    "compilerOptions": {
        "target": "es6",
        "module": "es6",
        "noEmitOnError": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "diagnostics": false,
        "noFallthroughCasesInSwitch": true,
        "noImplicitReturns": true,
        "traceResolution": false
    },
    "exclude": [
        "node_modules",
        "venue-finder"
    ]
}

Here is my webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const WebpackNotifierPlugin = require('webpack-notifier');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = [{
    bail: true,
    entry: {
        global: path.resolve(__dirname, 'js/responsive/global.ts'),
        todo: path.resolve(__dirname, 'js/todo/todo.ts'),
        budget: path.resolve(__dirname, 'Planner/javascript/Budget/BudgetPlannerUI.ts'),
        promotions: path.resolve(__dirname, 'js/promotions-management.ts'),
        planner: path.resolve(__dirname, 'Planner/javascript/MyPlanner.ts')
    },
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: '[name].js'
    },
    module: {
        rules: [{
            test: /\.ts(x?)$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'babel-loader',
                    options: {
                        'presets': [
                            ['env', {
                                'modules': false
                            }]
                        ]
                    }
                },
                {
                    loader: 'ts-loader'
                }
            ]
        }]
    },
    plugins: [
        new WebpackNotifierPlugin({ alwaysNotify: true }),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'commons',
            filename: 'commons-bundle.js',
            minchunks: 2
        }),
        new BundleAnalyzerPlugin()
    ],
    resolve: {
        extensions: ['.js', '.ts', '.tsx']
    },
    devtool: 'none'
}];

Even though the configuration seems correct, instead of moving pikaday, moment, and fancybox into commons-bundle.js, all three libraries are being included in each output file when I run webpack.

Your assistance with this matter would be greatly appreciated.

Answer №1

If you're looking to make the minChunks option a function instead of an integer value, consider this approach. Since fancybox, moment, and pickaday are sourced from node_modules, adjusting minChunks as shown below could be effective -

new webpack.optimize.CommonsChunkPlugin({
            name: 'commons',
            filename: 'commons-bundle.js',
            chunks: [global, todo, budget, promotions, planner], //optional, but a recommended practice
            minChunks: function (module) {
               return module.context && module.context.indexOf("node_modules") !== -1;
            }
        }),

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

Leveraging TypeScript's library extensions in combination with requirejs

Currently, I am experimenting with THREE.js and socket.io to develop a small game. I am looking to utilize the OrbitControls extension for THREE.js for camera controls, which I have successfully used in a previous project. However, it seems that the clien ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

Using a template reference variable as an @Input property for another component

Version 5.0.1 of Angular In one of my components I have the following template: <div #content>some content</div> <some-component [content]="content"></some-component> I am trying to pass the reference of the #content variable to ...

Problem with opening the keyboard feature in an Ionic app

Hello everyone, I'm relatively new to Ionic development and I've been trying to integrate a keyboard plugin into my application that opens from the footer and focuses on input fields for entering values. Here is the link to the plugin I used: ht ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

Firebase console does not show any console.log output for TypeScript cloud functions

I encountered an issue while using Typescript to write some Firebase cloud functions. Here is a snippet of my code: index.ts export * from "./Module1"; Module1.ts import * as functions from "firebase-functions"; export const test = functions.https.onR ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

What is the best way to access a state variable that has a union data type?

Is there a way to access a field of a state variable with a union type in TypeScript? Here is an example of a zustand store I have defined: import { create } from 'zustand' type HeightUnit = 'cm' | 'ft\' in"&ap ...

Is it possible to enable tooltips to function through the innerHTML method?

Currently, I am utilizing the innerHTML attribute to modify the inner HTML of a tag. In this instance, it involves the <td></td> tag, but it could be applied to any tag: <td *matCellDef="let order" mat-cell [innerHTML]="order. ...

Exploring the World of ESLint, Prettier, Typescript, and VScode Configuration

There is a common belief that Prettier is the preferred tool for formatting, while ESlint is recommended for highlighting linting errors, even though ESlint also has formatting capabilities. However, it should be noted that Prettier lacks certain advanced ...

Tips for integrating JavaScript libraries into TypeScript build process in Visual Studio

Is it possible to configure the "TypeScript Build" feature in Visual Studio 2017 to include both Javascript libraries and TypeScript files in the generated bundle.js output? ...

What is the best way to integrate the Telegram login widget into an Angular application?

Does anyone know how I can integrate the Telegram login widget into my Angular application without resorting to hacks? The required script is as follows: <script async src="https://telegram.org/js/telegram-widget.js?5" data-telegram-login="bot_name" ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Implementing the binding of components to another component post using forwardRef

I am looking to connect the Title and Body components with the Wrapper component. Previously, my component structure looked like this: import { FC } from 'react'; // binding required components const Title: FC<...> = () => {...} const ...

webpack - compile one TypeScript file separately (2 actions)

In summary... When my Vue files are combined with background.ts, webpack processes them to create bundled vue files along with background.js I'm unable to run the background.js script I expected background.js to only contain "console.log(' ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...