I've written several npm library projects, and this is the way I import symbols in one JS file from another JS file, but it won't work in the script section of a svelte file: My 'package.json' file has a name field (e.g. set to '@jdeighan/something`) and an 'exports' section with entries like "./utils": "./src/lib/utils.js". Then in any other JS file I can import symbols from utils.js with "import {somesymbol} from '@jdeighan/something/utils'. It's how to do imports from a library that you've installed with 'npm install', but it also (cleverly) works inside the project itself. But in a svelte file, this won't work - I get the error message "Failed to resolve import "@jdeighan/something/utils" from "src\routes page.svelte". Does the file exist?". Here is what I have in my svelte file:
<script>
import {somesymbol} from '@jdeighan/something/utils';
</script>
I know that svelte has a handy $lib
alias, but I'd prefer to use the npm standard mechanism, but it seems to be broken when using SvelteKit (not sure about using plain svelte)
CodePudding user response:
I'd prefer to use the npm standard mechanism
This is absolutely not the standard mechanism. I have never seen people import from the current project by package name. While this is supported by Node itself, nothing else seems to support it, including e.g. the VS Code language server which will be unable to provide code navigation.
Using the name makes it less clear that the import is local and not a separate dependency and if the name were to be changed it would have to be adjusted everywhere.
I would recommend just not doing that. SvelteKit has $lib
predefined as a default to provide essentially the same functionality in a convention-based way that actually works.
CodePudding user response:
If you create a project with just these 3 files, then execute node foo.js
in a console window, you get "Hello, World!":
package.json:
{
"name": "@jdeighan/something",
"type": "module",
"version": "1.0.0",
"exports": {
"./utils": "./utils.js"
}
}
foo.js:
import {message} from '@jdeighan/something/utils'
console.log(message);
utils.js
export let message = 'Hello, World!';