Search code examples
typescriptwebpackyarnpkgts-loaderyarnpkg-v2

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


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)
}

Solution

  • 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.