Adding local dependency in a Typescript project doesn't work when it works in JS
Asked Answered
E

1

2

I have been able to import a local package into a project by running yarn link ../path, which adds a resolution field to the package.json to tell the bundler where to find a package, basically giving it an alias.

Weird thing is that while this works when the file I'm doing the importing from is .jsx, not changing anything else, if I'm importing from .tsx, the module is not found.

So the culprit could be ts-loader, Typescript (how it treats imports), webpack, or yarn. I don't know if this is because I'm doing something wrong or this is a bug.

So the folder structure might be:

--ProjectMain
  ----/src
  ------index.jsx
  ----package.json

--ProjectToImport
  ----/src
  ------index.js
  ----package.json

I have the following in webpack.config.js in ProjectMain

module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /\.yarn/,
      },
      {
        test: /\.jsx?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react']
          },
        },
        exclude: /\.yarn/
      }
    ],
  },

ProjectToImport's index.js looks like

export function SharedLibTest(a){
  console.log(a)
}
Expecting answered 10/8, 2021 at 22:30 Comment(0)
E
2

Seems like the whole thing was because in my ProjectToImport/package.json, I used "main": "/src/index.js", instead of "main": "src/index.js"

I don't know why this makes a difference just because I'm using TS, may the wise among you enlighten me.

Expecting answered 12/8, 2021 at 19:46 Comment(1)
This literally saved me hours of debugging. ThanksLasandralasater

© 2022 - 2024 — McMap. All rights reserved.