в .tsx файле ошибка на импорте других .tsx файлов
Делаю проект через Webpack с использованием React и TypeScript. У меня есть main.tsx файл:
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import App from './App.tsx';
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Но есть проблема, при открытии файла main.tsx у меня подчёркивает красным строку с импортом App и выдаёт это: "An import path can only end with a '.tsx' extension when 'allowImportingTsExtensions' is enabled.ts(5097)", при этом проект запускается и работает нормально, хоть и показывает 1 ошибку. Когда я закрываю файл, ошибка пропадает, и соответственно появляется при открытии.
Как решить эту проблему, чтобы оно не жаловалось на импорт?
P.S: Кому нужно, вот мой webpack.config.js:
/**
* Webpack main configuration file
*/
const path = require("path");
const fs = require("fs");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const environment = require("./configuration/environment");
const templateFiles = fs
.readdirSync(environment.paths.source)
.filter((file) =>
[".html", ".ejs"].includes(path.extname(file).toLowerCase())
)
.map((filename) => ({
input: filename,
output: filename.replace(/\.ejs$/, ".html"),
}));
const htmlPluginEntries = templateFiles.map(
(template) =>
new HTMLWebpackPlugin({
inject: true,
hash: false,
filename: template.output,
template: path.resolve(environment.paths.source, template.input),
favicon: path.resolve(
environment.paths.source,
"assets",
"images",
"favicon.ico"
),
})
);
module.exports = {
entry: {
pp: path.resolve(environment.paths.source, "main.tsx"),
},
output: {
filename: "js/[name].js",
path: environment.paths.output,
},
module: {
rules: [
{
test: /\.((c|sa|sc)ss)$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
{
test: /\.(js|tsx|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.(png|gif|jpe?g|svg)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: environment.limits.images,
},
},
generator: {
filename: "images/design/[name].[hash:6][ext]",
},
},
{
test: /\.(eot|ttf|woff|woff2)$/,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: environment.limits.images,
},
},
generator: {
filename: "fonts/[name].[hash:6][ext]",
},
},
],
},
optimization: {
minimizer: [
"...",
new ImageMinimizerPlugin({
minimizer: {
implementation: ImageMinimizerPlugin.imageminMinify,
options: {
// Lossless optimization with custom option
// Feel free to experiment with options for better result for you
plugins: [
["gifsicle", { interlaced: true }],
["jpegtran", { progressive: true }],
["optipng", { optimizationLevel: 5 }],
// Svgo configuration here https://github.com/svg/svgo#configuration
[
"svgo",
{
plugins: [
{
name: "removeViewBox",
active: false,
},
],
},
],
],
},
},
}),
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css",
}),
new CleanWebpackPlugin({
verbose: true,
cleanOnceBeforeBuildPatterns: ["**/*", "!stats.json"],
}),
].concat(htmlPluginEntries),
target: "web",
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
};
Ответы (1 шт):
Ошибка сама говорит о проблеме. Импортировать файл с написанием .tsx можно только если в tsconfig.json стоит allowImportingTsExtensions: true.
Либо добавьте allowImportingTsExtensions: true в tsconfig.json, либо импортируйте без расширения .tsx