I’m using Babel with TypeScript and React (not sure if relevant). Index.js is able to import .ts file with no issues, but when I try importing .ts files from another .ts file,
(for example import testClass from "./testFile.ts"
)
I get the error: you cannot import files ending with .ts
.
Various search results either suggest it’s a bug or that you should just drop “.ts” from import (import testClass from "./testFile"
), but in that case I get an error about the file not being found. Suppose the solution lies within tsconfig.json, which looks like this:
{
"compilerOptions": {
// Target latest version of ECMAScript.
"target": "esnext",
// Search under node_modules for non-relative imports.
"moduleResolution": "node",
// Process & infer types from .js files.
"allowJs": true,
// Don't emit; allow Babel to transform files.
"noEmit": true,
// Enable strictest settings like strictNullChecks & noImplicitAny.
"strict": true,
// Import non-ES modules as default imports.
"esModuleInterop": true,
"jsx": "react"
},
"include": [
"src" // <-- change this to where your source files are
]
}
It might also have something to do with ForkTsCheckerWebpackPlugin
of webpack.congig.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
entry: './index.js',
mode: 'development',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js',
},
target: 'web',
devServer: {
port: '5000',
static: {
directory: path.join(__dirname, 'public')
},
open: true,
hot: true,
liveReload: true,
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
},
module: {
rules: [
{
test: /.(jpg)$/,
exclude: /node_modules/,
use: 'file-loader',
},
{
test: /.(ts|js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
plugins: [
new ForkTsCheckerWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html')
})
]
};