Strategies for incorporating a TypeScript-written Svelte library

UPDATE: The information in this question is no longer current. As of 12.8.2022, it is recommended to use the svelte-kit package available at .

I developed a library (https://github.com/TeemuKoivisto/svelte-tree-view) that I imported as a Svelte component in another project. While it worked fine when linked locally using yarn link svelte-tree-view, I encountered a strange error when using the npm downloaded version from node_modules:

[!] (plugin svelte) ValidationError: The $ prefix is reserved, and cannot be used for variable and import names
../node_modules/svelte-tree-view/src/TreeView.svelte
77:     rootElementStore.set(rootElement);
78: });
79: var $$$$$$$$ = null;
    ^
80: var $$vars$$ = [$$props, rootElement, $treeStore, treeStore, TreeNode_svelte_1.default];</script>

This error was challenging to troubleshoot due to limited online resources. However, I managed to find a simple solution and decided to share it here to assist others facing similar issues. Below are the key libraries relevant to resolving this problem:

    "rollup": "^2.56.3",
    "rollup-plugin-svelte": "^7.1.0",
    "rollup-plugin-ts": "^1.4.2",
    "svelte": "^3.42.6",
    "svelte-preprocess": "^4.9.4",
    "tslib": "^2.3.1",
    "typescript": "^4.4.3"

Answer №1

The issue you are encountering can potentially be resolved by updating to version 4.9.5 of svelte-preprocess. It seems like the problem lies in not being able to locate your tsconfig.json file, possibly because it is being searched for from a higher level directory, especially if you are working within a monorepo structure with the node_modules directory positioned above the project containing the tsconfig.json file.

As you rightly pointed out, the real solution lies in providing a preprocessed version of the library. This is crucial to avoid the need for users of your library to set up TypeScript preprocessing on their end, which can lead to unexpected errors like the one you are facing.

Thankfully, SvelteKit offers a convenient packaging command that takes care of preprocessing Svelte files (JS/HTML/CSS) and handling the TS to JS transpilation process. Additionally, it generates type definition files (d.ts) for these files, allowing you to continue developing your library in TypeScript while also delivering a user-friendly package for others to consume. For more detailed information, check out:

Answer №2

Now, the solution involves including a typescript block in your svelte.config.js file to define a tsconfigFile. The reasoning behind this addition is still somewhat unclear to me, but I am relieved that it ultimately resolves the issue.

Below is the complete svelte.config.js configuration:

const autoPreprocess = require('svelte-preprocess')

const preprocessOptions = {
  scss: { prependData: `@import 'src/global.scss';` },
  typescript: {
    tsconfigFile: './tsconfig.json'
  }
}

module.exports = {
  preprocess: autoPreprocess(preprocessOptions),
  preprocessOptions
}

UPDATE: Upon further investigation, it appears that creating TypeScript Svelte libraries is not recommended. This discovery means I will have to invest even more time into finding a solution. The struggles continue...

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

Encountered an issue resolving the dependency while executing npm i

I encountered an issue while trying to run the npm i command: npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a ...

Personalized prefix for Angular and WebStorm components

After starting a project in Angular with Visual Studio Code a few months ago, I decided to switch to WebStorm and upgraded the project to Angular 4.0 today. Although my project is running smoothly without any errors, I encountered an issue in WebStorm: ...

Discovering the appropriate node version for a project

Is it possible to determine the appropriate node version for a repository without resorting to trial and error? As web frameworks continue to evolve rapidly, revisiting projects from months or even years ago has become a common occurrence. I've foun ...

Using [file_id] as a dynamic parameter in nextjs pages

I am working with a nextjs-ts code in the pages/[file_id].tsx file. import Head from 'next/head'; import Script from 'next/script'; import Image from 'next/image'; import Link from 'next/link'; import { NextApiReques ...

Unable to navigate to a page called "meeting" in NextJS 13 due to issues with router.push not functioning correctly

import { Input, Button } from '@nextui-org/react'; import router from 'next/router'; import { SetStateAction, useEffect, useState } from 'react'; const SignIn = () => { const [errorMessage, setErrorMessage] ...

Issue detected - .xml2js.DELETE/package,json file corrupted within the node_modules of an Angular application

Issues arose following the update to Angular-Cli V10.1.0. The main difficulties I faced: The ng command was malfunctioning. It became apparent that essential dependencies were missing: npm WARN @angular/<a href="/cdn-cgi/l/email-prote ...

Organize elements within an array using TypeScript

I have an array that may contain multiple elements: "coachID" : [ "choice1", "choice2" ] If the user selects choice2, I want to rearrange the array like this: "coachID" : [ "choice2", "choice1" ] Similarly, if there are more tha ...

Help! Can't find a crucial file or plugin after setting up Cloud9 ide?

I am currently in the process of setting up Cloud9 on my Debian server for node.js development. I followed a set of simple steps outlined below, but it seems like something is missing and I need guidance on how to resolve this in the most effective way. Wh ...

Unable to get callback to function properly within request npm

I am facing some challenges with the callback function while using Request npm in my project. The API for users is built with Sailsjs, and I am using Reactjs for the front-end along with Request npm for communication with the API. There seem to be issues w ...

I am having an issue with the npm install command. Each time I try running it, I keep receiving an

After posting the output, I find myself unable to comprehend anything. Can someone please guide me on what steps to take next? npm has issued a warning about an old lockfile and advises that supplemental metadata needs to be fetched from the registry due t ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

What is the process for setting up Firebase tools on a Gitlab CI Runner?

Having issues configuring Gitlab CI to run firebase emulators, particularly with the installation of firebase-tools. Here is the relevant section from my config: unit-test-job: # This job runs in the test stage. image: node:14.14.0 artifacts: paths ...

Using Typescript, pass a Sequelize model as a property in NodeJS

Currently in the midst of a project using Node, Typescript, and Sequelize. I'm working on defining a generic controller that needs to have specific functionality: class Controller { Schema: <Sequelize-Model>; constructor(schema: <Sequel ...

Encountering errors when examining local variables during unit testing on an Angular component

If we have 2 components, namely AppComponent and TestComponent. The TestComponent is being called using its directive in the HTML template of the AppComponent. Within the TestComponent, there is an @Input() property named myTitle. Unit testing is being pe ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

The cache on GitHub Action has been successfully restored, however, the output indicates that it

Our approach involves caching our node_modules and running npm CI only if the cache is not found. This method functions properly on all branches except one, where even though the cache is restored, the output indicates a cache miss. We would greatly appre ...

The 'filter' property is not found on the type '{}'

I'm currently attempting to implement a custom filter for an autocomplete input text following the Angular Material guide. https://material.angular.io/components/autocomplete/overview Here's what I have so far: TS import { Component, OnInit } ...

Encountering ENOENT error when attempting to upgrade Node from version 6 to the latest one in a React Native project causes npm

When updating npm from version 6.14 to the latest on a React Native project, I am using Node.js 14, nvm to switch between Node versions. Ideally, I would like to upgrade to Node.js 16, but I encounter a similar issue regardless of whether it's versio ...

Mapping type property names in Typescript for substitution

I am working on a function that accepts two objects as parameters: one representing a model and the other representing a mapping. The function then returns an object with two properties: one showing the base model and the other displaying the model with ea ...

I encountered a 404 error when attempting to execute the "npm publish" command

While attempting to publish a package to the npm registry, an error is encountered after running the command npm publish. npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for buil ...