导入其他打字稿模块

时间:2017-08-02 20:36:38

标签: typescript node-modules

我正在尝试从nodes_modules中的typescript文件导入。该文件未被转换并使用typescript语法:

user.ts:

export const getUserFromToken = (token: string) => {
  return axios.get('/user', {
    headers: { authorization: `Bearer ${token}` }
  }).then(({ data }) => data)
}

我这样导入:import { getUserFromToken } from 'common-files/api/user',而common-files是在package.json中注册的模块。

在尝试编译时,我得到:

../commons/api/user.ts
Module parse failed: C:\Users\xxxx\Desktop\xxxx\commons\api\user.ts 
Unexpected token (9:38)
You may need an appropriate loader to handle this file type.
| export const getUserFromToken = (token: string) => {
|   return axios.get('/user', {
|     headers: { authorization: `Bearer ${token}` }

我认为,这导致它没有编译ts文件,因为当我删除字符串类型时,它会变成一个有效的es6文件,并且它会正确启动。

在我的tsconfig.json文件中,我有:

"exclude": [
  "node_modules",
  "build",
  "scripts",
  "acceptance-tests",
  "webpack",
  "jest",
  "src/setupTests.ts"
]

我在考虑,可能要排除node_modules,但包common-files除外,但不知道如何做到这一点。有没有一种方法可以实现我想要的东西?

2 个答案:

答案 0 :(得分:1)

@ShaunLuttin回答了一般情况的问题。我的问题是因为我使用了create-react-app和typescript脚本,他们的webpack配置不允许使用模块中的原始打字稿文件。我决定转换我的所有文件,并生成一个可用作模块的构建。它工作正常,但我确保在使用前端项目时不要包含仅在节点环境中有效的任何内容。

答案 1 :(得分:0)

  

旁白:您要做的事情是非常规的。通常,节点项目会安装已经转换为JavaScript的模块。

话虽如此,这里有一个适合您的设置a demo on GitHub.由于您的用例非常规,解决方案很复杂。

目录结构>请注意index.ts目录中的common-files文件。它有两个目的。首先,它将列出我们希望TypeScript转换的文件。其次,一旦被转换,index.js文件将告诉Node common-files文件夹是一个模块。 The Node documentation on Folders as Modules解释了Node如何解析模块。

node_modules    
  common-files
    api
      user.ts
    index.ts     <---- This file has two primary purposes.
index.ts        
package.json    
tsconfig.json   

node_modules / common-files / api / user.ts &gt;该文件包含我们要在您的应用程序中使用的声明。

export const getUserFromToken = (token: string) => {
    console.log("Getting the user for token " + token);
}

node_modules / common-files / index.ts &gt;根据NodeJS默认值,此index.ts文件是common-files模块的主文件。如前所述,主文件也将导入我们想要转换的每个声明。

import "./api/user";

index.ts &gt;此文件表示您正在构建的应用程序。我们可以导入common-files模块导出的任何已转换的声明。

import { getUserFromToken } from "common-files/api/user";

getUserFromToken("some-token");

package.json &gt;请注意,应用程序的节点包文件中没有任何特殊内容。也就是说,如果您使用npm install来安装common-files包,那么我们会在common-files部分中列出dependencies

{
  "dependencies": { }, 
  "devDependencies": {
    "typescript": "^2.4.2"
  }
}

tsconfig.json &gt; TypeScript配置有点复杂,因为需要转换common-files模块,我们想要排除node_modules中的所有其他内容。 tsconfig documentation详细了解了文件,包含和排除的互动方式。

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  },
  "files": [
    "node_modules/common-files/index.ts"
  ],
  "include": [
    "**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

上述设置的控制台输出如下所示:

> .\node_modules\.bin\tsc
> node index.js
Getting the user for token some-token