node.js - 如何正确使用 git+https 依赖
问题描述
我正在尝试使用 git+https 依赖项(在 github 上)来制作打字稿库。作为示例,我将其缩减为单个文件,但它仍然失败。使用文件依赖关系完美。切换到 git+https 依赖项会导致我收到错误消息:
export const Greeter = (name: string) => `Hello ${name}`;
^^^^^^
SyntaxError: Unexpected token 'export'
这两个依赖项,在任何一个项目中都没有其他变化:
"@dgmyers/greeter": "git+https://git@github.com:dgmyers/typescript-greeter-library.git#v0.1.1",
"@dgmyers/greeter": "file:../typescript-greeter-library",
文件:typescript-greeter-library/src/hello.ts
export const Greeter = (name: string) => `Hello ${name}`;
typescript-greeter-library/dist/hello.d.ts (tsc 生成)
export declare const Greeter: (name: string) => string;
typescript-greeter-library/package.json
{
"name": "typescript-greeter-library",
"version": "1.0.0",
"description": "",
"main": "src/hello.ts",
"types": "dist/hello.d.ts",
"scripts": {
"clean": "rm -rf dist/*",
"build": "tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/dgmyers/typescript-greeter-library.git"
},
"author": "",
"license": "UNLICENSED",
"bugs": {
"url": "https://github.com/dgmyers/typescript-greeter-library/issues"
},
"homepage": "https://github.com/dgmyers/typescript-greeter-library#readme"
}
typescript-greeter-library/tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"lib": ["es2020"],
"target": "es5",
"declaration": true,
"moduleResolution": "node",
"emitDeclarationOnly": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"baseUrl": "./node_modules",
"outDir": "./dist",
"module": "commonjs",
"typeRoots": [
"./types"
]
}
}
消费者/package.json
{
"name": "consumer",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"run": "ts-node src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "UNLICENCED",
"dependencies": {
"@dgmyers/greeter": "git+https://git@github.com:dgmyers/typescript-greeter-library.git#v0.1.2",
"@types/node": "^16.3.1",
"ts-node": "^10.1.0",
"typescript": "^4.3.5"
}
}
消费者/index.ts
import { Greeter } from '@dgmyers/greeter'
console.log(`${Greeter('dgmyers')}`);
解决方案
通过源代码库安装时,即。通过github:
orgit+https:
协议,npm 将运行prepare
生命周期脚本并像发布它一样打包它。
通常,即使您的源代码库不是纯 js(例如用 typescript 编写),它仍然可以,因为通常在其中配置用于编译源代码的脚本(例如 tsc),prepare
并且 npm 会在您安装代码库时编译它。
但是,仍然有两种情况会失败。
- 缺少编译脚本
prepare
- 缺少
.npmignore
源代码库中的文件,因此 npm 回退到.gitignore
该文件通常会排除包含已编译代码的文件夹
梅恩,你就是其中之一。