Danylkaaa
Danylkaaa

Reputation: 161

Import index(.ts|.js) file from folder in React

I have the following folder structure:

src/
   Foo/
      index.ts
   Bar/
      index.ts
   index.ts

I want import the module Foo like this import Foo from "./Foo"; in my src/index.ts file. How is this done? Because webpack doesn't autoimport the index.ts file from Foo/ and Bar/ when I want to "import folder".

Upvotes: 0

Views: 2797

Answers (1)

Milos Mosovsky
Milos Mosovsky

Reputation: 2983

You don't have to import folder as you mentioned. It's actually done by webpack resolve https://webpack.js.org/configuration/resolve/#resolve-extensions

By default webpack is looking for .js and .json extensions that means when you import import Foo from './Foo' it will try to look ./Foo/index.js or ./Foo/index.json if it is found, it is automatically imported. If you need to extend this to typescript you need to specify

resolve: {
 extensions: ['.js', '.json', '.ts']
}

of course in this way you have to specify ts-loader to handle typescript files https://github.com/TypeStrong/ts-loader which will take care of transpilation from typescript when it is imported.

Upvotes: 1

Related Questions