Webpack不会因TypeScript错误而失败

时间:2020-10-29 13:58:05

标签: typescript webpack ts-loader webpack-cli

自从我升级到版本5后,webpack不会因TypeScript错误而失败。

这是我的情况:

index.ts (入口点):

const message: string = "Hello World";
console.log(message);
  • 我运行./node_modules/.bin/webpack --config webpack.config.js --watch
  • 一切都很好。这是webpack的输出:
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
asset index.js 50 bytes [compared for emit] [minimized] (name: main)
./src/index.ts 65 bytes [built] [code generated]
webpack 5.0.0 compiled successfully in 1251 ms
[webpack-cli] watching files for updates...
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
asset index.js 50 bytes [emitted] [minimized] (name: main)
./src/index.ts 65 bytes [built] [code generated]
webpack 5.0.0 compiled successfully in 152 ms
[webpack-cli] watching files for updates...
  • 在下一步中,我添加一个代码片段,这将导致TypeScript错误:
const message: number = "Hello World"; // <= Type 'string' is not assignable to type 'number'.ts(2322)
console.log(message);
  • 我希望webpack监视过程失败或显示一些错误,但不会失败。这是webpack的输出:
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
asset index.js 50 bytes [emitted] [minimized] (name: main)
./src/index.ts 65 bytes [built] [code generated]
webpack 5.0.0 compiled successfully in 244 ms
[webpack-cli] watching files for updates...

有趣的是,这仅在启动webpack监视过程后更改index.ts时发生。如果我运行的Webpack不带--watch选项,我将得到以下输出,并且将不创建捆绑文件(如预期的那样):

[webpack-cli] Compilation finished
assets by status 50 bytes [cached] 1 asset
./src/index.ts 65 bytes [built] [code generated] [1 error]

ERROR in /Users/oliverschwendener/projects/test/src/index.ts
./src/index.ts
[tsl] ERROR in /Users/oliverschwendener/projects/test/src/index.ts(1,7)
      TS2322: Type 'string' is not assignable to type 'number'.

webpack.config.js

const path = require('path');

const config = {
    entry: './src/index.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ],
    },
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'bundle'),
    },
};

module.exports = config;

* edit:这是我的 tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "lib": ["dom", "es2017"],
    "sourceMap": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "moduleResolution": "node"
  }
}

我无法想象这是webpack,webpack-cli或ts-loader中的错误。所以我想我的配置有问题。谁能告诉我这是怎么回事?谢谢!

  • webpack 5.3.1(与所有webpack 4.44.2兼容)
  • webpack-cli 4.1.0
  • ts-loader 8.0.7
  • 打字稿4.0.5

2 个答案:

答案 0 :(得分:0)

在您的tsconfig.json中,您可以将noEmitOnError设置为true,以确保遇到错误时该过程可以中断:

{
    "compilerOptions": {
        "noEmitOnError": true,

(没有显式设置,默认为false

答案 1 :(得分:0)

没关系,这是ts-loader中的错误:https://github.com/TypeStrong/ts-loader/issues/1204