The npm package is unable to be imported

I've been working on a TypeScript project and wanted to incorporate the following library: https://github.com/Simonwep/pickr

According to the project instructions, I have performed the following steps:

import '@simonwep/pickr/dist/themes/nano.min.css';      // 'nano' theme
import {Pickr} from '@simonwep/pickr';

I also created a separate file where I declared the module:

declare module '@simonwep/pickr';

However, upon trying to use the library, I encountered this error in the Firefox console:

TypeError: pickr_min_1 is undefined

After some trial and error, I managed to fix the issue by using:

import Pickr from '@simonwep/pickr';

Now, when attempting to build the project, a new error surfaces:

[!] Error: 'default' is not exported by node_modules\@simonwep\pickr\dist\pickr.
min.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module

Being new to TypeScript and npm, I'm unsure about the correct approach for importing such projects into my TypeScript setup. Any guidance on this matter would be greatly appreciated.

Below are snippets of my configuration files:

//dev conf
import commoncfg from './conf-common';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
import copy from 'rollup-plugin-cpy';
import staticSite from 'rollup-plugin-static-site';

commoncfg[0].plugins.push(
    staticSite({
        template: { path: 'test.html' },
        dir: 'dist'
    }),
    copy({
        files: ['*.jpg'],
        dest: 'dist'
    }),
    serve('dist'),
    livereload()
);
// only generate UMD during dev
commoncfg[0].output.splice(0, 1);
commoncfg.pop();

export default commoncfg;

prod conf:

import { terser } from "rollup-plugin-terser";
import copy from 'rollup-plugin-cpy';

import commoncfg from './conf-common';


commoncfg[0].plugins.push(
    terser(),
    copy({
        files: ['LICENSE', 'README.md'],
        dest: 'dist'
    }),
    );
commoncfg[0].output.pop();
commoncfg[1].plugins.push(
    terser(),
);

export default commoncfg;

conf-common.js:

import pkg from './package.json';
import del from 'rollup-plugin-delete';
import typescript from 'rollup-plugin-typescript2';
import svgo from 'rollup-plugin-svgo';
import generatePackageJson from 'rollup-plugin-generate-package-json'
import postcss from 'rollup-plugin-postcss';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';

const outputDir = "./dist/";

let leanPkg = Object.assign({}, pkg);
leanPkg.scripts = {};
leanPkg.devDependencies = {};

const banner = 
`/* **********************************
Test
********************************** */`;

export default [
    {
        input: 'src/index.ts',
        plugins: [
            del({ targets: 'dist/*' }),
            typescript({
                useTsconfigDeclarationDir: true,
        clean: true
            }),
    nodeResolve(),
    commonjs({
      include: 'node_modules/**',  
      sourceMap: true, 
      namedExports: { 'node_modules/@simonwep/pickr' :['pickr'] }
    }),
            postcss(),
            svgo(),
            generatePackageJson({
                baseContents: leanPkg
            })],
        output: [
            {
                file: outputDir + pkg.module,
                format: 'es',
                banner: banner,
            },
            {
                file: outputDir + pkg.main,
                name: pkg.name,
                format: 'umd',
                sourcemap: true,
                banner: banner,
            },
        ]
    },
    {
        input: 'src/index.ts',
        plugins: [
            typescript({
                useTsconfigDeclarationDir: true,
        clean: true
            }),
            postcss({
          extensions: [ '.css' ]

        }),
            svgo(),
            generatePackageJson({
                baseContents: leanPkg
            })],
        output: [
            { 
                file: outputDir + pkg.main, 
                name: pkg.name, 
                format: 'umd',
                banner: banner
            },

        ]
    }
];

Answer №1

I am the creator of pickr,

Starting from version 1.4.5, official type declarations were added for those using it with TypeScript. As Nathan mentioned, using

import Pickr from '@simonwep/pickr';

is the correct way to import it and it should also work seamlessly with TypeScript. You can check out this codesanbox demo. Feel free to reach out if you encounter any issues or have any questions. I will update the Readme to include more TypeScript examples since it seems like many people are using pickr with TS :)

Unfortunately, I do not have experience with rollup. If you are able to set up a functional template, you could submit an issue detailing how you achieved it.

The error of "Pickr.create is not declared" is indeed a bug. It will be addressed in the upcoming patch release.

Answer №2

Make sure your installation is correct by running the following command:

npm install @simonwep/pickr

Then, in your module where you want to use the pickr library, import it along with the necessary styling at the top of your file like this:

import '@simonwep/pickr/dist/themes/nano.min.css';      // 'nano' theme
import Pickr from '@simonwep/pickr';

Note: According to the documentation, make sure to load the JavaScript file after the CSS file. Also, note that you should use default import instead of a named export. For example:

import Pickr from '@simonwep/pickr';

Instead of:

import { Pickr } from '@simonwep/pickr';

Next, instantiate the pickr object within your module to start using it. Here's an example configuration:

const pickr = Pickr.create({
    el: '.color-picker',
    theme: 'classic', // or 'monolith', or 'nano'

    swatches: [
        // List of colors
    ],

    components: {
        // Components configuration
    }
});

You can listen for events triggered by the pickr object by using event listeners such as:

pickr.on('init', instance => {
    console.log('init', instance);
}).on('hide', instance => {
    console.log('hide', instance);
}).on('show', (color, instance) => {
    console.log('show', color, instance);
})

I hope this explanation helps!

Answer №3

Encountered a similar issue while working with TypeScript 3.6.

Resolved it by importing using '* as'

import * as Pickr from '@simonwep/pickr';

The Pickr.create({...}) method ran successfully.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There appears to be a problem with an unexpected or invalid token in EmberJS, but

It's quite baffling, really. I innocently added a single line of CSS and suddenly everything went haywire. I even attempted to delete the entire CSS file I was tinkering with, but to no avail. Below is the snippet from the .log file: ERROR Summary: ...

Hey Webapp: Access denied - unable to open 'Gruntfile.js' due to permissions

Ever since I switched to Linux, I have been encountering the "Error EACCESS, permission denied" message whenever I try to install any Yeoman generator. fs.js:432 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); ...

Can you explain how to utilize the cp .env.local env command effectively?

Could someone break down this process for me in simple terms? I'm attempting to install an Ethereum application from Github and the folder I downloaded comes with these instructions: Clone this repository cp .env.local .env npm install npm start W ...

If the condition is met, convert the number in JSON format to text

i have retrieved a JSON array from an API: items:[{ Name: "Status" Value: "3" },{ Name: "Status" Value: "2" }, { Name: "Status" Value: "1" }] then I extract the data ...

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

Disregarding extraneous object attributes that come with a Back-End object

Seeking advice on how to handle unnecessary object properties that come with a Back-End model. Could you please share your thoughts? Imagine an API returning the following object: export class TodoObject{ public name: string; public id: number, publi ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Navigating through directories with a specific string using a shell script

I currently have 10 directories named client-1, client-2,..., client-10, along with another directory named nestjs-wrapper. My goal is to automate the process of navigating into each client directory, running npm install and node index.js within each one. ...

Steps for removing the ag-grid-community software from your system

I need assistance removing the ag-grid-community package from my React project. Despite attempting multiple npm uninstall commands, such as npm uninstall -g --force --save ag-grid-community, the package remains in both node_modules and package.json. The ...

Steps to update npm to the newest version: Even though Ubuntu indicates a successful installation, it may not actually upgrade the version

I have a gcloud compute instance running ubuntu 18.04 lts minimal with npm installed. However, after using apt-get to install npm, it only gave me version 3.5.2. When I try to update to the latest npm version using npm install npm@latest -g, it asks me t ...

Error with Firebase on Apple's M1 Mac devices

I recently upgraded my MacBook Air to the M1 chip. Firebase was functioning properly until I updated firebase-tools from version 9.7.0 to 9.8.0 last week. Since the update, I encounter an error anytime I attempt to execute a "firebase" command. This quest ...

Apologies for the inconvenience, but it seems that the build is not successful at the moment. For help with resolving common issues, please refer

ERROR CODE ERESOLVE ERROR: Unable to resolve Error Error Resolving: @material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec888d988dc18b9e8588acd8c2dcc2dcc18d809c848dc2dfdb">[email protected] ...

How can I rectify the issue in TypeScript where the error "not all code paths return a value" occurs?

While developing an application, I encountered an error that says: "not all code paths return a value". The error is specifically in the function named addValues, indicating that the function must return "Obj[] | undefined". Here is the code snippet in qu ...

Spring Boot receiving null values from Angular form submission

I am currently working on a form in Angular that is used to submit information such as author, context, and recently added images. However, I have run into an issue where I am able to successfully retrieve the author and context, but not the images (it alw ...

Tips for resolving TypeScript object undefined error when utilizing object of model classes

I encountered an issue while working with an object of a class that retrieves data from an API. When trying to access this object in the HTML, I'm receiving error TS2532. Here is the relevant code snippet-- export interface TgtInfo{ Mont ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Is it possible for the app-routing.module.ts to have two paths with :/id?

When attempting to access the maindetail and childdetails pages using :/id, I encountered an issue on localhost where the desired card was not displaying on the maindetail page. The goal is to be able to click on the name "aniq" in the dashboard (image 1) ...

Simplifying imports in Angular, the easy way: A guide to stream

We recently made a change to our Angular project by moving the npm-library @ng-plus/modal to live as a project library under the project/ngplus-modal folder. One issue we encountered is with the imports within the project. Even though we previously def ...

React JS hosted externally along with just plain Javascript and HTML page

We are looking to implement a common widget on multiple services using ReactJS. The goal is to write client-side code for this widget as an external hosted JavaScript file that can be included in pages across different frameworks such as Angular, Inferno, ...

Receive notification indicating that the function is of void type

As a newcomer to angular, I am currently in the process of setting up my authorization module for an ionic project I am developing. I have made significant progress, but I have encountered an issue with the 'auth' service that I created. Within ...