首页 > 解决方案 > 包在项目中没有正确导入

问题描述

我最近创建了一个 Typescript 包,我想在发布到 NPM 之前在应用程序中进行测试。

入口文件 (index.ts) 看起来像这样 =>

import Builder from './core/builder';

export default Builder;

基本上,有很多文件,但我希望用户只使用Builder我在索引中导出的“静态”类。所以用户可以做import Builder from 'builderts'

我的package.json文件夹如下

  "name": "builderts",
  "main": "./dist/builderts.js",
  "types": "./dist/builderts.d.ts",
  "files": [
    "dist/*"
  ],
  "scripts": {
    "preversion" : "npm run lint",
    "prepare": "npm run build",
    "prepublishOnly": "npm test && npm run lint",
    "version" : "npm run format && git add -A src",
    "postversion" : "git push && git push --tags",
    "build": "tsc",
    "watch": "tsc-watch",
    "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
    "lint": "eslint tsconfig.json"
  },

和我的tsconfig.json

{
    "compilerOptions": {
      "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
      "module": "amd",                          /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
      "declaration": true,                      /* Generates corresponding '.d.ts' file. */
      "declarationMap": true,                   /* Generates a sourcemap for each corresponding '.d.ts' file. */
      "sourceMap": true,                        /* Generates corresponding '.map' file. */
      "outFile":"./dist/builderts.js",              /* Concatenate and emit output to single file. */
      "outDir": "dist",                         /* Redirect output structure to the directory. */
      "strict": true,                           /* Enable all strict type-checking options. */
      "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
      "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
    },
    "include": ["src"],
    "exclude": ["node_modules", "dist"]
}

我面临的问题是,我尝试创建一个小型测试项目并使用

npm install absolute/path

它安装正确,但是当我尝试使用导入包时

import Builder from 'builderts';

我没有自动完成功能,我有一个错误说

文件“D:/User/Local/gitRepo/builderts/dist/builderts.d.ts”不是模块。

我不太明白我在这个过程中缺少什么。

标签: javascripttypescriptnpmpackage

解决方案


types在我看来,您需要更新package.json

你上面说的文件名是index.ts,你考虑过更新package.json吗?:

{ 
...
"types": "./dist/index.ts",
...
}

推荐阅读