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

Filtering an array dynamically in Typescript depending on the entered value

My task involves filtering arrays of objects based on input field values. Data data: [{ taskname: 'Test1', taskId: '1', status: 'Submitted' }, { taskname: 'Test2', taskId: '2', status: 'Re ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Angular Fails to Identify Chart.js Plugin as an Options Attribute

Encountering issues with using the 'dragData' plugin in Chart.js 2.9.3 within an Angular environment: https://github.com/chrispahm/chartjs-plugin-dragdata After importing the plugin: chartjs-plugin-dragdata, I added dragdata to the options as sh ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Enhancing Type Safety in Typescript through Key/Property Type Guards

Is it possible to create a typeguard that can confirm the existence (or specific type) of a property in an object? For example: Consider an interface Foo: interface Foo { bar: string; baz: number; buzz?: string; } An object of type Foo may ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

What is the best approach for implementing line coverage for object literal in Typescript Mocha unit-tests?

Lead: I am a newcomer to using typescript and writing unit tests with Mocha and Chai. Question: Can anyone provide tips on achieving 100% line coverage in unit tests for an object literal that isn't within a class? I want to avoid going static if pos ...

What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways: // For TypeScript or Babel import myutils from 'myutils' // myuti ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Error: In Typescript, it is not possible to assign the type 'false' to type 'true'

Currently, I am exploring Angular 2 and encountered a situation where I set the variable isLoading to true initially, and then switch it to false after fetching required data. However, upon executing this process, I encountered the following error message: ...

Creating and managing global context with useReducer in TypeScript and React

One issue that I am facing is with the route containing a login and logout button, where the browser error states 'Property 'dispatch' does not exist on type '{}'. (home.tsx) import React, { useContext, useEffect, useRef, use ...

Function Type Mapping

I am in the process of creating a function type that is based on an existing utility type defining a mapping between keys and types: type TypeMap = { a: A; b: B; } The goal is to construct a multi-signature function type where the key is used as a ...

Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code: <swal #saveSwal title="Are you sure?" text ="Do you want to save changes" cancel ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...