0

我已经设法通过 Webpack 将 Typescript 添加到我的 React 项目中,但是当我遇到类型错误时,Webpack 无论如何都会编译。例如,这里我给一个数值赋值一个字符串,Visual Studio Code 指示错误,但 Webpack 仍然编译它:

let num: number = 123;

num = "Hello!!"; // <- Error, but webpack still compiles it.

export const App: FC = () => {
    return (
        <div>
            <h1>Welcome to React App!!!</h1>
        </div>
    );
};

当发生类型错误时,我希望 webpack 不编译它,所以,首先必须在编译之前解决错误,我该如何实现呢?这是我的配置:

package.json

{
  "name": "react-webpack-template",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "prod::watch": "webpack --watch --mode production",
    "dev::watch": "webpack --watch --mode development"
  },
  "devDependencies": {
    "@babel/core": "^7.16.0",
    "@babel/preset-env": "^7.16.4",
    "@babel/preset-react": "^7.16.0",
    "@babel/preset-typescript": "^7.16.0",
    "@types/react": "^17.0.37",
    "@types/react-dom": "^17.0.11",
    "babel-loader": "^8.2.3",
    "css-loader": "^6.5.1",
    "mini-css-extract-plugin": "^2.4.5",
    "style-loader": "^3.3.1",
    "typescript": "^4.5.2",
    "webpack": "^5.64.4",
    "webpack-cli": "^4.9.1"
  },
  "dependencies": {
    "@linaria/babel-preset": "^3.0.0-beta.13",
    "@linaria/core": "^3.0.0-beta.13",
    "@linaria/react": "^3.0.0-beta.13",
    "@linaria/shaker": "^3.0.0-beta.13",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  }
}

babel.config.json

{
    "presets": [
        "@babel/preset-env",
        [
            "@babel/preset-react",
            {
                "runtime": "automatic"
            }
        ],
        "@babel/preset-typescript"
    ]
}

tsconfig.json

{
    "compilerOptions": {
        "target": "es2016",
        "jsx": "react-jsx",
        "module": "commonjs",
        "moduleResolution": "node",

        "removeComments": true,

        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,

        "strict": true,

        "alwaysStrict": true,

        "noImplicitOverride": true,
        "skipLibCheck": true
    },
    "include": ["src/**/*", "src/*"],
    "exclude": ["node_modules"]
}

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { join } = require('path');

/** @type {import('webpack').Configuration} */
module.exports = {
    entry: join(__dirname, 'src', 'index.tsx'),

    output: {
        path: join(__dirname, 'build'),
        filename: '[name]/[name].js'
    },

    resolve: {
        extensions: ['.js', '.ts', '.jsx', '.tsx']
    },

    devtool: 'source-map',

    module: {
        rules: [
            {
                test: /\.t(s|sx)$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            },
            {
                type: 'assets',
                test: /\.(png|jpg|svg)$/
            }
        ]
    },

    plugins: [new MiniCssExtractPlugin()]
};

我希望你能帮帮我 :)

4

0 回答 0