Home > Net >  Webpack 'production' mode compiles nothing
Webpack 'production' mode compiles nothing

Time:12-14

I followed the typescript guide: https://webpack.js.org/guides/typescript/ When I run webpack with "production" mode, it emitted almost nothing.

Here is the source code of my src/index.ts file:

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

Then I run the command:

webpack

I got the 'bundle.js' file compiled into the 'dist' folder, the code is:

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

But if go to the 'src' folder and compile with the 'tsc' command, it generate the javascript file with the following code:

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

I think both 'dist/bundle.js' and the 'src/index.js' file should be the same, at least the functionality. But now 'dist/bundle.js' file doesn't work at all.

And bellow are the code of 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"
  }
}

Can anyone help me? Thank you.

CodePudding user response:

Using webpack in production mode will drop dead code via tree shaking.

foo function and bar variables are unused export that should be dropped. That is what's known as "dead code".

If you create another file that uses the bar variable.

import { bar } from "./index";

console.log(bar);

The bundle.js output will be:

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

TypeScript just erases the types and compiles the code to target JavaScript language version such as es5, it has no tree-shaking conception.

  • Related