在 Typescript 项目中添加本地依赖在 JS 中工作时不起作用 [英] Adding local dependency in a Typescript project doesn't work when it works in JS

查看:28
本文介绍了在 Typescript 项目中添加本地依赖在 JS 中工作时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够通过运行 yarn link ../path 将本地包导入到项目中,这会向 包添加一个 resolution 字段.json 告诉打包器在哪里可以找到一个包,基本上是给它一个别名.

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.

奇怪的是,当我从 .jsx 导入的文件时,这有效,但如果我从 .tsx 导入,则不会更改任何其他内容>,未找到模块.

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.

所以罪魁祸首可能是 ts-loader、Typescript(它如何处理导入)、webpack 或 yarn.我不知道这是因为我做错了什么还是这是一个错误.

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

我在 ProjectMain 的 webpack.config.js 中有以下内容

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 的 index.js 看起来像

ProjectToImport's index.js looks like

export function SharedLibTest(a){
  console.log(a)
}

推荐答案

似乎整个事情是因为在我的 ProjectToImport/package.json 中,我使用了 "main": "/src/index.js", 而不是 "main": "src/index.js"

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

我不知道为什么这会因为我使用 TS 而有所不同,请你们中的聪明人启发我.

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

这篇关于在 Typescript 项目中添加本地依赖在 JS 中工作时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆