导入其他打字稿模块
我正在尝试从打印节点模块中的打字稿文件导入。这个文件是不是transpiled并使用打字稿语法:导入其他打字稿模块
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
,但不知道该怎么做。有没有一种很好的方法来实现我想要的?
旁白:你想要做的是非常规的。通常,节点项目会将已经转换成JavaScript的模块进行安装。
就这么说,这里有一个适合你的设置和a demo on GitHub.由于你的用例非常规,解决方案很复杂。
目录结构>请注意common-files
目录中的index.ts
文件。它有两个目的。首先,它会列出我们希望TypeScript进行传输的文件。其次,一旦它被转发,index.js
文件将告诉节点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 /共文件/ API/user.ts>此文件包含我们想在你的应用程序中使用的声明。
export const getUserFromToken = (token: string) => {
console.log("Getting the user for token " + token);
}
node_modules /共文件/ index.ts>根据默认的NodeJS,这index.ts文件是common-files
模块的主要文件。如前所述,主文件也将导入我们想要传输的每个声明。
import "./api/user";
index.ts>此文件表示你正在构建的应用程序。我们可以导入common-files
模块导出的任何传输声明。
import { getUserFromToken } from "common-files/api/user";
getUserFromToken("some-token");
的package.json>请注意,有没有什么特别的在应用程序的节点包文件。也就是说,如果您使用npm install
来安装common-files
包,那么我们将在dependencies
部分列出common-files
。
{
"dependencies": { },
"devDependencies": {
"typescript": "^2.4.2"
}
}
tsconfig.json>打字稿配置有些复杂,因为你的common-files
模块需要transpiled,我们要排除一切内部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
你说这是非常规的,也许有传统的方法来实现我想要的?我想要两个单独的包共享一些代码,因此我已将该代码移动到npm包并在本地将它们导入到每个项目中。在使用其他软件包时,npm软件包没有被转发的问题。 –
@VincasStonys答案搁置了传统方法。 –
我坐下来,走到你建议的步骤,但他们没有任何区别,因为我得到了同样的错误。也许我的目录结构在某种程度上是无效的,或者其他配置是干预的...如果你觉得自己有帮助,这里是我的repo链接:https://github.com/vincaslt/language-exchange/tree/EnvFix with the fixes根据你的回答 –
@ShaunLuttin回答了这个问题的一般情况。我的问题是因为我用typescript脚本使用create-react-app,并且他们的webpack配置不允许使用来自模块的原始打字稿文件。我决定编译所有的文件,并生成一个可以作为模块使用的版本。它工作正常,但是我确保在使用前端项目时不要包含仅在节点环境中工作的任何内容。
我假设这是一个自定义模块?模块需要自己编译并发布.js和.d.ts。你在这里看到的问题确实是tsc没有编译这个文件(它怎么知道把它放在哪里),然后webpack(?)解决了由于某种原因导入到.ts文件... –
你如果您使用ts-node而不是节点,则可以包含ts文件而不进行转译。 – lilezek