微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何防止 webpack 为未使用的模块抛出 typescript 错误?

如何解决如何防止 webpack 为未使用的模块抛出 typescript 错误?

我有以下结构:

└── src
    ├── tsconfig.json
    ├── core
    │   ├── [...].ts
    └── ui
        ├── [...].tsx
        └── tsconfig.json

在前端,我从核心导入了少量模块。这些模块以及任何依赖模块都符合这两个 tsconfig 文件

tsc 和 eslint 没有错误地通过,webpack 构建所需的输出文件。到目前为止一切顺利。

然而,当 webpack 构建时,它会为其他后端模块抛出大量类型错误

如何抑制这些错误?我尝试从 src/core 中排除 babel-loader 并包含所需的模块,但我仍然遇到相同的错误

/// webpack.config.js
/* eslint-disable @typescript-eslint/no-var-requires */

const path = require('path');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',entry: './src/ui',output: {
    path: path.resolve(__dirname,'./ui-dist'),},// Enable sourcemaps for debugging webpack's output.
  devtool: 'source-map',resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: ['.ts','.tsx','.js','.jsx'],module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,exclude: /node_modules/,use: {
          loader: 'babel-loader',options: {
            cacheDirectory: true,babelrc: false,presets: [
              [
                '@babel/preset-env',{ targets: { browsers: 'last 2 versions' } },// or whatever your project requires
              ],'@babel/preset-typescript','@babel/preset-react',],plugins: [
              // plugin-proposal-decorators is only needed if you're using experimental decorators
              //  in TypeScript
              ['@babel/plugin-proposal-decorators',{ legacy: true }],['@babel/plugin-transform-runtime',['@babel/plugin-proposal-class-properties',{ loose: true }],'react-hot-loader/babel',// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      {
        enforce: 'pre',test: /\.js$/,loader: 'source-map-loader',plugins: [
    new ForkTsCheckerWebpackPlugin({
      tsconfig: path.resolve(__dirname,'./src/ui/tsconfig.json'),eslint: true,/** Options to supply to eslint https://eslint.org/docs/developer-guide/nodejs-api#cliengine */
      // eslintOptions: EslintOptions;
    }),new HtmlWebpackPlugin({
      title: 'development',template: './src/ui/template.html',}),// When importing a module whose path matches one of the following,just
  // assume a corresponding global variable exists and use that instead.
  // This is important because it allows us to avoid bundling all of our
  // dependencies,which allows browsers to cache those libraries between builds.
  // externals: {
  //   react: 'React',//   'react-dom': 'ReactDOM',// },devServer: {
    contentBase: path.resolve(__dirname,};

编辑:我想我是通过使用 import type { x } from '../core/index.ts' 来引用这些模块的。也许我需要找到一种方法babel-loader 跳过扫描类型导入。

解决方法

删除 ForkTsCheckerWebpackPlugin 就成功了。在任何情况下调用 tsc 时都会进行类型检查。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。