0

I am learning typescript and I would love to begin experimenting packages creation.

Here is my folder structure for the moment:

myProject/
├── node_modules/
├── src/
│   ├── app
│       ├── index.ts
│   ├── packages
│       ├── database
│           ├── index.ts
├── package.json
├── tsconfig.json

As you can see, my src folder is divided into app that will contain my application implementation and a package folder that is supposed to be more "abstract", in order to become one day a package eventually.

What I would like, would be to access to my packages modules writing the following in my app folder:

import Database from 'packages/database';

instead of

import Database from '../packages/database/index';

I looked around the paths configuration into the tsconfig.json file but I could not get it to work:

{
  "compilerOptions": {

    ...

    "baseUrl": ".",
    "paths": {
      "packages": ["src/packages"]
    }
  }
}

I would also like to keep access to the node_modules folder of course...

How could I achieve that?

Thank your for your replies

1 Answer 1

1

I think that the best solution for you would be to divide your work into several packages:

For example, you would have a package-database package that would make all the database related work for you.

In order to do that, you need to modify your structure a little bit:

myProject/
├── node_modules/
├── src/
│   ├── app
│       ├── index.ts
│   ├── packages
│       ├── database
│           ├── SomeClass.ts
│           ├── index.ts
├── package.json
├── tsconfig.json

Then make all the exports in your database/index.ts file:

import SomeClass from './SomeClass'
import SomeOtherClass from './SomeOtherClass'

export {SomeClass, SomeOtherClass}

You would the be able to access it from your app folder typing:

import {SomeClass} from 'package-database';

Of course, you also need to modify your tsconfig.json, you were close to it:

{
    "compilerOptions": {

    ...

    "baseUrl": ".",
    "paths": {
        "package-database": ["src/packages/database"]
        }
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.