52

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!

Guilherme Chiara
  • 1,154
  • 2
  • 12
  • 15
  • There's an example [on the typescript website](https://www.typescriptlang.org/docs/handbook/react-&-webpack.html) that imports without the extension: `import { Hello } from "./components/Hello";`. Perhaps that's the future approach? It's quite annoying as it's lost intellisense in vs code... – NickL Dec 15 '16 at 15:06

8 Answers8

45

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'
jahsome
  • 881
  • 8
  • 18
  • 1
    Worked for me. Also don't forget the `./` – AirOne Mar 17 '22 at 12:16
  • 37
    Removing the `.ts` causes a `Cannot find module` for me – Jtcruthers Aug 06 '22 at 10:25
  • 2
    For me, this causes a different warning: ECMAScript requires file extension on relative import. Why the standard does that I've no idea. – A. L. Flanagan Sep 10 '22 at 22:13
  • Is there a specific configuration you have to set up in order for this to work? I'm getting errors on my browser console when I try to load my webpage: `GET http://localhost/static/js/panes/MDlgSettings [HTTP/1.1 404 NOT FOUND 8ms]` and `Loading module from “http://localhost/static/js/panes/MDlgSettings” was blocked because of a disallowed MIME type (“text/html”).` – elkshadow5 May 17 '23 at 00:24
  • 2
    if you guys are getting `ERR_MODULE_NOT_FOUND` error (like @Jtcruthers mentioned) when trying this solution try adding a .js extension instead of .ts in the import and it should fix the error. – Dremiq May 23 '23 at 12:13
16

This is what I use and it works pretty well.

Full webpack config here: https://gist.github.com/victorhazbun/8c97dc578ea14776facef09a115ae3ad

webpack.config.js

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

module.exports = {
  ...
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  ...
};
victorhazbun
  • 786
  • 8
  • 16
  • 3
    This link is broken. – ThomasReggi Jun 20 '20 at 06:38
  • 1
    The link may be broken but the cod provide still makes sense. If you're running webpack you can add the resolve option as shown and this will resolve the ts extension. If you're started a new project, then yes, maybe integrate webpack and utilise this method. – Sandy Garrido Apr 18 '21 at 17:41
2

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.

FarazShuja
  • 2,287
  • 2
  • 23
  • 34
1

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.

Elsa
  • 153
  • 1
  • 6
1

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

yashhy
  • 2,856
  • 5
  • 31
  • 57
0

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.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Shammoo
  • 1,084
  • 10
  • 22
0

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
jordanbtucker
  • 5,768
  • 2
  • 30
  • 43
BuGaGa
  • 302
  • 2
  • 9
0

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'.
Rui Ying
  • 809
  • 8
  • 12