Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't import the library in Node #5

Closed
havaliza opened this issue Jul 8, 2022 · 6 comments
Closed

Can't import the library in Node #5

havaliza opened this issue Jul 8, 2022 · 6 comments

Comments

@havaliza
Copy link

havaliza commented Jul 8, 2022

I'm really looking forward to use PocketBase. Great project.

Here is what happened when I tried to require the library in Node:

Welcome to Node.js v18.3.0.
Type ".help" for more information.
> require("pocketbase")
/Users/[REDACTED]/node_modules/pocketbase/dist/pocketbase.es.js:1
function t(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}var e={exports:{}},r=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},n=r,o=Object.prototype.toString;function i(t){return"[object Array]"===o.call(t)}function a(t){return void 0===t}function s(t){return null!==t&&"object"==typeof t}function u(t){if("[object Object]"!==o.call(t))return!1;var e=Object.getPrototypeOf(t);return null===e||e===Object.prototype}function c(t){return"[object Function]"===o.call(t)}function l(t,e){if(null!=t)if("object"!=typeof t&&(t=[t]),i(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.call(null,t[o],o,t)}var p={isArray:i,isArrayBuffer:function(t){return"[object ArrayBuffer]"===o.call(t)},[REDACTED],set:function(t){this.http.defaults.baseURL=t.replace(/\/+$/,"")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"language",{set:function(t){t?this.http.defaults.headers.common["Accept-Language"]=t:delete this.http.defaults.headers.common["Accept-Language"]},enumerable:!1,configurable:!0}),t.prototype.cancelRequest=function(t){return this.cancelSource[t]&&(this.cancelSource[t].cancel(),delete this.cancelSource[t]),this},t.prototype.cancelAllRequests=function(){for(var t in this.cancelSource)this.cancelSource[t].cancel();return this},t.prototype.send=function(t){var e,r,n,o=Object.assign({},t);if((null===(e=this.AuthStore)||void 0===e?void 0:e.token)&&void 0===(null===(r=null==o?void 0:o.headers)||void 0===r?void 0:r.Authorization)){var i="Admin";void 0!==(null===(n=this.AuthStore.model)||void 0===n?void 0:n.verified)&&(i="User"),o.headers=Object.assign({},o.headers,{Authorization:i+" "+this.AuthStore.token})}return this.http.request(o)},t}();export{yn as Admin,Pn as Collection,mn as LocalAuthStore,dn as Record,Rn as Request,An as SchemaField,hn as User,Nn as default};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

Uncaught SyntaxError: Unexpected token 'export'

I also got this error when importing PocketBase in an empty Vite app:

✘ [ERROR] Do not know how to load path: pocketbase

7:49:09 PM [vite] error while updating dependencies:
Error: Build failed with 1 error:
error: Do not know how to load path: pocketbase
@ganigeorgiev
Copy link
Member

ganigeorgiev commented Jul 8, 2022

Thanks for reporting the issue. The bundle issues were resolved in v0.1.2 release.

To load for node.js environment, now it should be enough to do:

const PocketBase = require("pocketbase");

OR if you are using es6 style imports (suitable also for the browser if you are using a bundler like rollup and webpack):

import PocketBase from "pocketbase";

More details could be also found in the Installation readme section

If you are still experiencing issues, please let me know and I'll try to investigate it further.

@jcyh0120
Copy link

I got import problem when using a simple typescript file running with ts-node. My project require using typescript with commonjs.

// index.ts
import PocketBase from "pocketbase";
export const db = new Pocketbase("http://localhost:8090");

When running ts-node, It throws an error

Error [ERR_REQUIRE_ESM]: require() of ES Module ../node_modules/pocketbase/dist/pocketbase.es.mjs not supported.
Instead change the require of ../node_modules/pocketbase/dist/pocketbase.es.mjs to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (../src/db/db.ts:7:38)
    at Module.m._compile (../node_modules/ts-node/dist/index.js:857:29)
    at Object.require.extensions.<computed> [as .ts] (../node_modules/ts-node/dist/index.js:859:16)
    at phase4 ../node_modules/ts-node/dist/bin.js:466:20)
    at bootstrap (../node_modules/ts-node/dist/bin.js:54:12)
    at main ../node_modules/ts-node/dist/bin.js:33:12)
    at Object.<anonymous> (../node_modules/ts-node/dist/bin.js:579:5) {
  code: 'ERR_REQUIRE_ESM'
}

Here's my tsconfig.

{
  "compilerOptions": {
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "src",                                  /* Specify the root folder within your source files. */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    "outDir": "dist",                                   /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */

    "strict": true,                                      /* Enable all strict type-checking options. */
    "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": ["src"]
}

I also run ts-node with following import cjs path but still got an error of

import Pocketbase from "pocketbase/dist/pocketbase.cjs";

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './dist/pocketbase.cjs' is not defined by "exports" in ../node_modules/pocketbase/package.json

if I import with import Pocketbase from "pocketbase/cjs". The typescript complain

Cannot find module 'pocketbase/cjs' or its corresponding type declarations.

Thanks for the awsome project.

@ganigeorgiev
Copy link
Member

@jcyh0120

This was recently discussed in #34.

In short you have 2 options:

  1. Use the CommonJS bundle. The correct import statement is:

    const PocketBase = require('pocketbase/cjs');

    For other node caveatas, see the Installation section in the readme - https://github.com/pocketbase/js-sdk#installation

  2. OR change your TS config to allow esm imports - Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules/pocketbase/dist/pocketbase.es.mjs not supported. #34 (comment)

@jcyh0120
Copy link

jcyh0120 commented Sep 22, 2022

@ganigeorgiev Thanks for directing me to the right discussion. I've tried option1 it works!

The only problem left is missing type definition when using const PocketBase = require('pocketbase/cjs')

I'll try to find a workaround for this. Thanks Again!

@mandrillxx
Copy link

@ganigeorgiev Thanks for directing me to the right discussion. I've tried option1 it works!

The only problem left is missing type definition when using const PocketBase = require('pocketbase/cjs')

I'll try to find a workaround for this. Thanks Again!

Did you ever find a solution? None of the esnext/module type works for me. Having type definitions would be nice

@TylerBarnes
Copy link

if you can't enable esm for some reason you can make a helper like this to get the imported module and the type:

export const getPocketBase = async () => {
  const { default: PocketBase } = await import("pocketbase")
  return PocketBase
}

export type PocketBaseType = Awaited<
  ReturnType<typeof getPocketBase>
>["prototype"]

then use it like:

import { getPocketBase, PocketBaseType } from "get-pocketbase"


function foo() {
  const PocketBase = await getPocketBase()

  // do stuff with pb here
}

// if you need the type elsewhere
function doAThingWithProvidedPocketBaseClient(pb: PocketBaseType) {
  // pb will be typed as a pocket base client here
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants