In the production mode, Webpack doesn't compile any code

I recently followed the typescript guide at https://webpack.js.org/guides/typescript/ After running webpack in "production" mode, I noticed that it emitted very minimal output.

Below is the code from my src/index.ts file:

export function foo() {
  return 'foo'
}
export const bar = 'bar'

When I executed the command:

webpack

I found that the 'bundle.js' file was compiled into the 'dist' folder with the following code:

(()=>{"use strict";})();

However, when I manually compiled using the 'tsc' command inside the 'src' folder, I got a JavaScript file with the following content:

"use strict";
exports.__esModule = true;
exports.bar = exports.foo = void 0;
function foo() {
    return 'foo';
}
exports.foo = foo;
exports.bar = 'bar';

I expected both the 'dist/bundle.js' and 'src/index.js' files to have similar functionality. But currently, the 'dist/bundle.js' file is not functioning properly.

Additionally, here are snippets of code from other related files:

// package.json
{
  "name": "webpack-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^9.2.6",
    "typescript": "^4.5.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  }
}
// webpack.config.js
const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};
// tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node"
  }
}

If anyone can offer assistance, I would greatly appreciate it. Thank you.

Answer №1

When using webpack in production mode, dead code is eliminated through a process called tree shaking.

The foo function and bar variables are examples of unused exports that will be removed. This is commonly referred to as "dead code".

If you create another file that utilizes the bar variable.

import { bar } from "./index";

console.log(bar);

The resulting bundle.js output would look like this:

(()=>{"use strict";console.log("bar")})();

Unlike TypeScript, which simply removes types and compiles down to a specific target JavaScript language version like es5, it does not have the ability to perform tree-shaking.

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

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

A step-by-step guide on integrating PDF.js with Vue 3 and accessing the distribution folder locally

I must clarify that I am restricted from using any vue libraries to preview PDFs; only pure pdf.js and vue 3 are permitted. Utilizing pdf.js for presenting PDF files within my vue 3 project. Inquiring about the ideal folder structure for the project to en ...

Retrieving and storing data using jQuery's AJAX caching feature

When utilizing jQuery's $.ajax() method to perform an XHR based HTTP GET request to obtain a partial of HTML from a Ruby on Rails website, I encounter an issue. Specifically, every time a user clicks on tabbed navigation, I refresh an HTML table with ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

Develop a specialized data structure for rows in ag grid that can adapt to changes

I have been working on creating an independent component using ag-grid. The column definitions are passed to this component from my application as input properties, defined like this: interface ColumnDef { field: string; headerName: string; } @Input() ...

What steps can I take to avoid an invalid operation on a potentially null reference in typescript?

Take a look at this scenario where the variable a can potentially be null, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation - let a: string | null = "hello" function ...

What could be causing the npm server error in my Vue.js application?

After recently setting up Node.js and Vue.js, I decided to dive into my first project on Vue titled test. As part of the process, I attempted to configure the server using the command: npm run server However, I encountered the following error message: C ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

Passing an object from @CanActivate() to a component in Angular 2 leads to Typescript Error

Within Angular 2, I am using a MyObjectComponent to display an array of myObjects. These myObjects are retrieved from a MyObjectService, which is called by @CanActivate. @CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => { ...

Unable to locate component property

When passing props to my component that link to storybook, I encountered an issue where the object I pass in does not map, resulting in the error message: "TypeError: data.map is not a function". I realized that my object is not actually an &qu ...

Discovering the method to retrieve the values from 2 dropdown lists that are populated by a JavaScript function

I have a pair of dropdown lists in a JSP file labeled 'speciality' and 'super_speciality'. Clicking on an option in the 'speciality' dropdown list dynamically populates options in the 'super_speciality' dropdown list ...

Any number of elements in a single JSX code snippet

In my React code, I've created a function called optionTemplate to be used as a prop in a React component. const optionTemplate = (option) => { return ( <div className="flex align-items-center gap-2" style={ ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...