网站搜索

javascript - Webpack '生产' 模式没有编译任何内容


我按照 TypeScript 指南操作:https://webpack.js.org/guides/typescript/ 当我以“production”模式运行 webpack 时,它几乎没有输出任何内容。

这是我 src/index.ts 文件的源代码:

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

然后我运行命令:

webpack

我已将 'bundle.js' 文件编译到 'dist' 文件夹中,代码是:

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

但是如果进入 'src' 文件夹并使用 'tsc' 命令进行编译,它会生成包含以下代码的 JavaScript 文件:

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

我认为 'dist/bundle.js' 和 'src/index.js' 文件应该是一样的,至少功能上应该一致。但现在 'dist/bundle.js' 文件根本无法工作。

下面是其他相关文件的代码:

// 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"
  }
}

有人能帮我吗?谢谢。

答案#1

在 production 模式下使用 webpack 会通过 tree shaking 删除无用代码。

foo 函数和 bar 变量是未使用的导出,应该被移除。这就是所谓的“死代码”。

如果你创建另一个使用 bar 变量的文件。

import { bar } from "./index";

console.log(bar);

bundle.js 输出将是:

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

TypeScript 只是擦除类型并将代码编译为目标 JavaScript 语言版本,如 es5,它没有树摇的概念。