【问题标题】:How to ignore files from being compiled if they are not bein used如果不使用文件,如何忽略它们的编译
【发布时间】:2022-11-30 04:25:05
【问题描述】:

我正在构建一个 TypeScript 项目,我想在其中根据某些条件生成输出文件(对于实际项目,它取决于 env)。我在下面给出了一个简化的代码示例。 我正在使用 webpack 来构建项目。

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();
}

在上述情况下,由于编译器永远不会转到else 块,因此来自testComponent.ts 的代码永远不会编译到输出文件中。以下是我得到的输出

(() => {
  "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");
})();

供您参考,webpack如下

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",
  };
};

有人可以帮我吗?

提前致谢

我希望来自 testComponent.ts 的代码不会出现在输出中。

【问题讨论】:

    标签: typescript webpack dead-code tree-shaking


    【解决方案1】:

    goTo是:

    • let,即可变
    • 变量

    如果你想让它摇树化,它应该是const goTo或者if (true)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      相关资源
      最近更新 更多