Накопительный пакет распространяет определения TypeScript для библиотеки Javascript - PullRequest
0 голосов
/ 04 июня 2019

Меня попросили добавить определения типов TypeScript для экспортируемых модулей в библиотеке JavaScript, созданной с помощью Rollup.

Я написал .d.ts файлы рядом, и теперь я думаю, что мне нужно настроить сведение(или некоторый плагин), чтобы взять эти определения и перенести их (в конечном итоге объединить?) в каталог dist.

Библиотека организована следующим образом:

MyLib
|_/dist
| |_ index.js
| |_ index.js.map
|
|_/src
| |_/componentA
| | |_ index.js
| | |_ index.d.ts
| |
| |_/componentB # this is not exported, thus no use of TS.
| | |_ index.js
| |
| |_/componentC
|   |_ index.js
|   |_ index.d.ts  
|_ index.js
|_ package.json
|_ rollup.config.js
|
|_ etc...

Я искал проблемы, читал документацию Rollup и искал проблемы в репозитории Rollup, но не смог найти ничего полезного.

Пример файла:

import * as React from 'react'

declare class Launcher extends React.Component<LauncherProps, any> {}

export interface LauncherProps {
  brandSvg: string;
  documentationUrl?: string;
  // ...
}

export default Launcher

package.json:

{
  "name": "MyLib",
  "version": "1.0.0",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "jsnext:main": "dist/index.es.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "build": "rollup -c",
    "ci": "env CI=true yarn lint && yarn coverage",
    "coverage": "yarn test --coverage --watchAll=false",
    "dev": "rollup -c -w",
    "dev:start-example": "cd ./example && npm run start",
    "lint": "eslint src --ext .js",
    "prepare": "yarn run build",
    "predeploy": "cd example && yarn install && yarn run build",
    "test": "cross-env CI=1 react-scripts test --env=jsdom",
    "test:watch": "react-scripts test --env=jsdom"
  },
  "files": [
    "dist"
  ],
  "dependencies": {
    "fast-levenshtein": "^2.0.6",
    "prop-types": "^15.7.2",
    "ramda": "^0.26.1"
  }
  "peerDependencies": {
    "antd": "^3.18.2",
    "prop-types": "^15.5.4",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/plugin-external-helpers": "^7.2.0",
    "@babel/plugin-proposal-class-properties": "^7.4.4",
    "@babel/polyfill": "^7.2.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/preset-react": "^7.0.0",
    "@svgr/rollup": "^2.4.1",
    "antd": "^3.18.2",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^9.0.0",
    "babel-jest": "^23.6.0",
    "babel-plugin-import": "^1.11.2",
    "babel-plugin-react-docgen": "^3.1.0",
    "cross-env": "^5.1.4",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.13.1",
    "enzyme-react-intl": "^2.0.4",
    "eslint": "5.12.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-config-standard-react": "^7.0.2",
    "eslint-plugin-babel": "^5.3.0",
    "eslint-plugin-import": "^2.17.3",
    "eslint-plugin-jest": "^22.6.4",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.1.1",
    "eslint-plugin-react": "^7.13.0",
    "eslint-plugin-standard": "^4.0.0",
    "npm-run-all": "^4.1.5",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-intl": "^2.8.0",
    "react-scripts": "^2.1.8",
    "rollup": "^0.64.1",
    "rollup-plugin-babel": "^4.3.2",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-node-builtins": "^2.1.2",
    "rollup-plugin-node-resolve": "^3.3.0",
    "rollup-plugin-peer-deps-external": "^2.2.0",
    "rollup-plugin-postcss": "^2.0.3",
    "rollup-plugin-url": "^2.2.1"
  },
}

Файл конфигурации накопительного пакета rollup.config.js выглядит следующим образом:

import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import builtins from 'rollup-plugin-node-builtins'
import url from 'rollup-plugin-url'
import svgr from '@svgr/rollup'
import typescript from 'rollup-plugin-typescrip2'

import pkg from './package.json'

export default {
  input: 'src/index.js',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      sourcemap: true,
      external: ['path']
    },
    {
      file: pkg.module,
      format: 'es',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({
      modules: false
    }),
    url(),
    svgr(),
    babel({
      exclude: 'node_modules/**',
      plugins: [ '@babel/external-helpers' ]
    }),
    builtins(),
    resolve(),
    commonjs(),
    typescript() // <-- added later
  ]
}

ОБНОВЛЕНИЕ

  1. В соответствии с предложением @darklightcode, которое я обновил в ответе package.json добавив:
  "typings": "dist/index.d.ts",
  "typescript": {
    "definition": "dist/index.d.ts"
  },

и соответственно создал файл tsconfig.json:

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "dist"
  }
}

Запуск сценария сборки по-прежнему ничего не дает.

Использование rollup-plugin-typescript2 (конфигурация выше) приводит к следующей ошибке:
[!] Error: Unknown object type "asyncfunction"
Error: Unknown object type "asyncfunction"
    at Object._object (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:218:17)
    at Object._function (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:319:14)
    at Object.dispatch (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:185:30)
    at /home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:246:18
    at Array.forEach (<anonymous>)
    at Object._object (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:242:21)
    at Object.dispatch (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:185:30)
    at /home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:260:23
    at Array.forEach (<anonymous>)
    at Object._array (/home/fredmaggiowski/Development/mylib/node_modules/rollup-plugin-typescript2/node_modules/object-hash/index.js:259:20)

1 Ответ

0 голосов
/ 04 июня 2019

В вашем package.json используйте следующие клавиши для указания на ваши .d.ts файлы:

{
   ...
  "typings": "definitions/index", // change the path to your main .d.ts
  "typescript": {
    "definition": "definitions/index" // change the path to your main .d.ts
  }
  ...
}

PS: ниже tsconfig.json, так что вы можете составить представление о том, где tsconfig.json экспортирует файлы определений и то, на что указывает package.json.Пути могут быть изменены по вашему желанию.

  {
  "compilerOptions": {
    "listEmittedFiles": false,
    "outDir": "lib",
    "declaration": true, 
    "declarationDir": "definitions",
    "module": "commonjs",
    "target": "es6",
    "noImplicitAny": true,
    "noImplicitThis": true,
    "removeComments": false,
    "suppressImplicitAnyIndexErrors": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "pretty": true,
    "allowJs": true,
    "jsx": "react",
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "./node_modules/**/*"
  ]
}

PSS: убедитесь, что ваши наборы не будут создавать конфликтов с другими типами, заключите их в пространство имен.

...