Angular 8 и Stripe. js loadStripe V3: Модуль не найден: Ошибка: Не удается разрешить '@ stripe / stripe-js / types / index' - PullRequest
0 голосов
/ 31 марта 2020

Я использую Stripe в качестве обработчика платежей, и они предоставляют библиотеку, которая позволяет разработчикам создавать безопасные «элементы» (входные данные кредитных карт и тому подобное). Чтобы оставаться PCI-совместимым с рейтингом A, предоставляемая ими библиотека Stripe. js не может быть связана: она должна быть включена с их сайта: https://js.stripe.com/v3. Таким образом, они предоставляют вспомогательную функцию loadStripe, которую можно использовать для динамического включения вышеупомянутого сценария. (Он просто добавляет тег <script> и ожидает его загрузки под капот. Ничего особенного.)

https://github.com/stripe/stripe-js

Я смог установить эту библиотеку через NPM и заставьте Stripe работать в моем Angular 8 проекте. Я сделал функцию loadStripe провайдером, чтобы я мог смоделировать ее во время тестирования. Вот уменьшенная версия того, что я делаю.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { loadStripe } from '@stripe/stripe-js';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],  
  imports: [
    BrowserModule,
  ],  
  providers: [
    {provide: loadStripe, useValue: loadStripe},
  ],  
  bootstrap: [
    AppComponent,
  ]
})
export class AppModule { }

Работает отлично. Я могу использовать loadStripe в своих сервисах и смоделировать его в своих модульных тестах. Но когда я пытаюсь сделать производство сборки (ng build --prod), я получаю неприятную, криптную c ошибку.

ERROR in ./src/app/app.module.ngfactory.js
Module not found: Error: Can't resolve '@stripe/stripe-js/types/index' in '/home/<MY-USER>/temp/test-stripe/src/app'
resolve '@stripe/stripe-js/types/index' in '/home/<MY-USER>/temp/test-stripe/src/app'
  Parsed request is a module
  using description file: /home/<MY-USER>/temp/test-stripe/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in /home/<MY-USER>/temp/test-stripe/
        using description file: /home/<MY-USER>/temp/test-stripe/package.json (relative path: .)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: /home/<MY-USER>/temp/test-stripe/package.json (relative path: ./@stripe/stripe-js/types/index)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.js doesn't exist
            as directory
              /home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index doesn't exist
      /home/<MY-USER>/temp/test-stripe/src/app/node_modules doesn't exist or is not a directory
      /home/<MY-USER>/temp/test-stripe/src/node_modules doesn't exist or is not a directory
      /home/<MY-USER>/temp/node_modules doesn't exist or is not a directory
      /home/<MY-USER>/node_modules doesn't exist or is not a directory
      /home/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
      looking for modules in /home/<MY-USER>/temp/test-stripe/node_modules
        using description file: /home/<MY-USER>/temp/test-stripe/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/package.json (relative path: ./types/index)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.js doesn't exist
            as directory
              /home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index doesn't exist
[/home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index]
[/home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.ts]
[/home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.tsx]
[/home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.mjs]
[/home/<MY-USER>/temp/test-stripe/@stripe/stripe-js/types/index.js]
[/home/<MY-USER>/temp/test-stripe/src/app/node_modules]
[/home/<MY-USER>/temp/test-stripe/src/node_modules]
[/home/<MY-USER>/temp/node_modules]
[/home/<MY-USER>/node_modules]
[/home/node_modules]
[/node_modules]
[/home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index]
[/home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.ts]
[/home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.tsx]
[/home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.mjs]
[/home/<MY-USER>/temp/test-stripe/node_modules/@stripe/stripe-js/types/index.js]
 @ ./src/app/app.module.ngfactory.js 13:0-52 14:2720-2733
 @ ./src/main.ts
 @ multi ./src/main.ts

Я могу предоставить StackBlitz, если это необходимо, но Приложение, на которое ссылаются выше, буквально по умолчанию ng new test-stripe с npm install @stripe/stripe-js@1.2.x.

FWIW, ng build и ng serve работают, как и ожидалось, просто сбой сборки prod. Если я удалю провайдера loadStripe, приложение создаст приложение (то есть, если я просто импортирую loadStripe в свои сервисы напрямую).

Спасибо за любую помощь.

1 Ответ

0 голосов
/ 02 апреля 2020

Я нашел три способа исправить это.

  1. В Angular Формат пакета , добавление записи «typings» в модуль @stripe/stripe-js устранило проблему. (В файле package.json модуля уже есть запись "type", но, очевидно, она не поддерживается в Angular 8.)
  2. Вручную добавьте путь для @ stripe / stripe- js в compilerSettings раздел tsconfig.json файла.
"paths": {
  "@stripe/stripe-js": [
    "node_modules/@stripe/stripe-js/dist/stripe.js"
  ]
}
Обновление до Angular 9 - путь, по которому я в конечном итоге пошел.
...