Как предотвратить выдачу webpack ошибок машинописного текста для неиспользуемых модулей?

У меня есть следующая структура:

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

Во фронтенд я импортирую небольшое количество модулей из ядра. Эти модули и любые зависимые модули совместимы с обоими файлами tsconfig.

tsc и eslint проходят без ошибок, а 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', { legacy: true }],
              ['@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, './ui-dist'),
  },
};

РЕДАКТИРОВАТЬ: я полагаю, что я ссылаюсь на эти модули, выдающие ошибку, используя import type { x } from '../core/index.ts'. Возможно, мне нужно найти способ для babel-loader пропустить импорт типа сканирования.


person user247298    schedule 18.02.2021    source источник
comment
Я попытался использовать плагин new webpack.IgnorePlugin(/.*/, /.*core.*/), но те же ошибки по-прежнему возникают, несмотря на то, что какой-либо файл в ядре был исключен из выходного файла.   -  person user247298    schedule 19.02.2021


Ответы (1)


удаление ForkTsCheckerWebpackPlugin помогло. Проверка типов выполняется при вызове tsc в любом случае.

person user247298    schedule 19.02.2021