Guilherme Chiara
Guilherme Chiara

Reputation: 1444

An import path cannot end with '.ts' - NodeJS and Visual Code

I've got an error while trying to build a simple NodeJS app:

enter image description here

Even that Visual Code prompts an error, my code got running.. When I remove the .ts extension from import statement, I got an error that the file cannot be found.

I'm using webpack, but these files are from server. Here's my folder structure:

enter image description here

And here's my webpack file:

var webpack = require('webpack');
var helpers = require('./helpers');

//# Webpack Plugins
var CopyWebpackPlugin = (CopyWebpackPlugin = require('copy-webpack-plugin'), CopyWebpackPlugin.default || CopyWebpackPlugin);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
var ExtractTextPlugin = require('extract-text-webpack-plugin');

//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'My Application',
  baseUrl: '/',
  host: process.env.HOST || '0.0.0.0',
  port: process.env.PORT || 8080,
  ENV: ENV,
  HMR: HMR
};

//# Webpack Configuration
module.exports = {
  metadata: METADATA,

  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.ts',
  },

  resolve: {
    extensions: ['', '.ts', '.tsx', '.js', '.scss'],
    root: helpers.root('src'),
    modulesDirectories: [
      'node_modules',
      'server'
    ]
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material'),
          helpers.root('node_modules/@angular')
        ]
      }

    ],

    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.scss|css$/,
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' }),
        exclude: [ helpers.root('node_modules') ]
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, 
        loader: "url-loader?limit=10000&mimetype=application/font-woff" 
      },
      { 
        test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        loader : 'file-loader'
      }
    ]
  },

  plugins: [

    new ForkCheckerPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(true),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),

    new ExtractTextPlugin("[name].css"),

    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    }),

    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      "Tether": 'tether',
      "window.Tether": "tether"
    })

  ],
  
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};

Can anybody help me? Tks!

Upvotes: 81

Views: 97115

Answers (11)

Ajay Rathod
Ajay Rathod

Reputation: 21

Create an tsconfig.json file at root.

Add this in code in file

{
  "compilerOptions": {
    "target": "es5",  //tell which version you are using
    "baseUrl": "./",
    "esModuleInterop": true, //this is required to solve your issue
    "jsx": "react-jsx", //this is required to solve your issue
    "noEmit": true, //this is required to solve your issue
    "allowImportingTsExtensions": true //this is required to solve your issue
  },
  "include": ["src"]
}

Upvotes: 1

Sungharsh J
Sungharsh J

Reputation: 61

To fix .ts extension import error, as per

https://www.typescriptlang.org/tsconfig/#allowImportingTsExtensions

"compilerOptions":{
  "allowImportingTsExtensions": true,//this works only with below noEmit set to true
  "noEmit": true,
}

Upvotes: 3

Michael Schmid
Michael Schmid

Reputation: 4997

In your TS config, set

"compilerOptions": {
  …
  "moduleResolution": "bundler",
}

You can then remove the “.ts” extension

Upvotes: 1

victorhazbun
victorhazbun

Reputation: 841

This is what I use and it works pretty well.

webpack.config.js

'use strict';
const webpack = require('webpack');

module.exports = {
  ...
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  ...
};

Upvotes: 19

BuGaGa
BuGaGa

Reputation: 449

To solve your problem, you need:

  1. Make sure that you have a tsconfig.json file in the project.json with code
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}
  1. Check or create a react-app-env.in.ts file with the code
/// <reference types="react-scripts" />

It is this react-app-env.d.ts file that explains TypeScript how to work with ts, tsx, and so on file extensions

enter image description here

  1. Remove tsx file extensions in imports. Also remove all extensions that TypeScript will swear at

For example before:

import { Header } from "./Header.tsx";

This should be the case after removing extensions:

import { Header } from "./Header";
  1. If you had a project running at the time of these changes, stop it and start it again. Since these changes are applied only when the project is started at the compilation stage

Upvotes: 0

Rui Ying
Rui Ying

Reputation: 879

You may need to import abc/xyz.js even if the source file is abc/xyz.ts when using TypeScript with ESM.

This gets rid of both errors:

  • An import path can only end with a .ts extension when allowImportingTsExtensions is enabled.
  • Relative import paths need explicit file extensions in EcmaScript imports when --moduleResolution is node16 or 'nodenext'.

Upvotes: 1

yashhy
yashhy

Reputation: 3086

None of the above solutions worked. Adding allowImportingTsExtensions in tsconfig.json solved the issue.

My full answer here: https://stackoverflow.com/a/76332913/1778834

Note that I had this issue in the context of Webdriver

Upvotes: 9

FarazShuja
FarazShuja

Reputation: 2370

For me the case was VSCode was using different Typescript version where as the workspace was dependent on different version. Need to select the one from the workspace.
Click on version in the status bar:
enter image description here

and select the version from the workspace.

Upvotes: 3

jahsome
jahsome

Reputation: 1441

I had this issue and it took me the better part of an hour to realize all I had to do was remove the .ts extension from the import. For me:

 // index.ts
import { renderSection, useConfig, writeToFile } from './hooks.ts'

// changed from `./hooks.ts` to `./hooks`
import { renderSection, useConfig, writeToFile } from './hooks'

Upvotes: 95

Elsa
Elsa

Reputation: 193

I had the same problem and the solution for me was to just re-run the application. In my case, I had just finished converting some files to .tsx, perhaps it explains it.

Upvotes: 2

Shammoo
Shammoo

Reputation: 1103

I'm not sure what the exact solution to this question is. Apparently, the solution is to remove the .ts extension — it is a configuration issue if it cannot find the file. For me the configuration issue was resolved when I started using ts-loader.

Upvotes: 0

Related Questions