Prasad Naik
Prasad Naik

Reputation: 1

How to ignore files from being compiled if they are not bein used

I am building a TypeScript project where I have want to generate output file depending on some conditions (For the actual project it depends on env). I am giving a simplified code example below. I am using webpack to build the project.

testComponent.ts

export const someComponent = () => {
  console.log("This is Some Component");
};

index.ts

import { someComponent } from "./components/testComponent";

let goTo = 1;

if (goTo === 1) {
  console.log("Will go to this");
} else {
  someComponent();
}

In above case, since compiler will never go to else block, code from testComponent.ts should never get compiled into output file. Following is the output I am getting

(() => {
  "use strict";
  var o = {
      310: (o, e) => {
        Object.defineProperty(e, "__esModule", { value: !0 }),
          (e.someComponent = void 0),
          (e.someComponent = function () {
            console.log("This is Some Component");
          });
      },
    },
    e = {};
  function t(n) {
    var r = e[n];
    if (void 0 !== r) return r.exports;
    var s = (e[n] = { exports: {} });
    return o[n](s, s.exports, t), s.exports;
  }
  t(310), console.log("Will go to this");
})();

For your reference, webpack is as follow

const path = require("path");

const bundleOutputDir = "./dist";

module.exports = (env) => {
  return {
    entry: "./src/index.ts",
    output: {
      filename: "output.js",
      path: path.resolve(bundleOutputDir),
    },
    devServer: {
      contentBase: bundleOutputDir,
    },
    plugins: [],
    module: {
      rules: [
        {
          test: /\.ts?$/,
          use: "ts-loader",
          exclude: /node_modules/,
        },
      ],
    },
    resolve: {
      extensions: [".ts", ".js"],
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    mode: "production",
  };
};

Can someone help me out?

Thanks in advance

I am expecting code from testComponent.ts to not appear in output.

Upvotes: 0

Views: 273

Answers (1)

Dimava
Dimava

Reputation: 10899

goTo is:

  • let, i.e. changeable
  • variable

If you want to make it tree-shakeable it should be const goTo or maybe if (true)

Upvotes: 0

Related Questions