Importing a JS npm library in Svelte - javascript

I don't understand how to import a random npm library in Svelte.
Take the scrapegoat library for example, a library to read CalDAV objects. I created a brand new Svelte project:
$ npx degit sveltejs/template my-svelte-project
$ cd my-svelte-project/
$ npm install
$ npm install -D scrapegoat
Not sure if it should be added to the devDependencies but it doesn't seem to make a lot of difference if it is not. Now, in the src/App.svelte I add this singe line in the existing <script> tag.
import scrapegoat from 'scrapegoat'
Running npm run dev throws the following error:
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
node_modules/scrapegoat/package.json (2:9)
1: {
2: "_from": "scrapegoat#^2.0.0",
^
3: "_id": "scrapegoat#2.0.0",
4: "_inBundle": false,
Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
at error (node_modules/rollup/dist/shared/rollup.js:158:30)
at Module.error (node_modules/rollup/dist/shared/rollup.js:12420:16)
at Module.tryParse (node_modules/rollup/dist/shared/rollup.js:12823:25)
at Module.setSource (node_modules/rollup/dist/shared/rollup.js:12726:24)
at ModuleLoader.addModuleSource (node_modules/rollup/dist/shared/rollup.js:22197:20)
This is what I understood from Rich Harris' reply but I am clearly missing something.

The package you’re importing imports its own package.json. Rollup won’t handle JSON imports by default, so you will need to install the json plugin and add it to your Rollup config.

Related

cannot import or require node modules (using npm)

Versions
I am working on a relatively old Laravel 7 project.
npm -v
8.15.0
node -v
v14.17.1
The Issue
I installed a new package using npm
npm i my_new_package
and am now trying to import the package from my js:
<script type="module" src="/js/filename.js"></script>
filename.js:
import { Roulette } from "my_new_package";
// Uncaught TypeError: Failed to resolve module specifier "#theblindhawk/roulette".
// Relative references must start with either "/", "./", or "../".
const Roulette = require("my_new_package");
// Uncaught ReferenceError: require is not defined
I tried a bunch of stuff from other SO questions, but none of it seemed to work.
There were no issues when I tried creating a file in the same repository and calling it.
import { Roulette } from "./different_file.js";
I am guessing this has to do with CommonJS/ES6, but my knowledge about these is quite lacking.
I messed up at the very basics...
Probably cuz I was recently working on a Laravel project with an different file creation method.
I forgot I had to put my js files in the resouces folder, then call them from the webpack.mix.js.
The webpack file:
mix.js('resources/js/filename.js', 'public/js')
Then run npm run watch and it will create the files inside the public folder for you.

Jest not recognising JQuery Object ($)

I have used JavaScript to created a simple web application to measure how much time I spend on different projects.
I want to test the code with Jest and this works fine until I try to test a function that contains the JQuery object ($).
This is the error message I get:
ReferenceError: $ is not defined
The answers I have found online tells me that I need to add a jQuery dependency in my global object, which I have done. Below is my package.json file:
"jest": {
"setupFiles": ["PathToSetupFile/setup-jest.js"],
"type": "module"
and my setup-jest.js:
import $ from 'jquery';
global.$ = global.jQuery = $;
I am now met with a new error message:
SyntaxError: Cannot use import statement outside a module
I cannot find any further information on how to fix this. A few resources tell me I need to update my jest.config.js file but this file does not exist anywhere in my node modules.
I thought it would be helpful to start completely from the beginning and therefore address a much wider scope but never the less provide the exact answer to your problem at the end of my response here.
In PowerShell CD to your project folder
Install the jest node modules locally into your project folder using
npm install --save-dev jest
Install jest globally so you can use it as a CLI command
npm install jest -g
This installs Jest globally i.e. to your user profile %APPDATA%\npm location
Ensure %APPDATA%\npm is in your user profile environment PATH variable (in Windows settings, "Edit Environment variables for your account")
Check in your PowerShell console that it is in your path using $Env:PATH. (If your %APPDATA%\npm path still isn't showing then restart the PowerShell window, if the terminal is inside VSCode then you will have to restart VSCode so that the terminal inherits the new environment)
In order to import jquery you will need to a) install jquery and b) define a setup file for jest which is referenced in jest.config.js created using jest --init in your project folder.
Install jquery -
npm install --save-dev jquery
Generate jest.config.js -
jest --init
The following questions will help Jest to create a suitable configuration for your project
√ Would you like to use Typescript for the configuration file? ... no
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » v8
√ Automatically clear mock calls, instances, contexts and results before every test? ... yes
✏️ Modified your\project\folder\package.json
📝 Configuration file created at jest.config.js
If you don't specify the jsdom (browser-like) test environment then running code under test that uses jquery will yield an error of "jQuery requires a window with a document"
But this means the 'jest-environment-jsdom' must now be installed
(As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.) -
npm install --save-dev jest-environment-jsdom
Edit jest.config.js
Change
// setupFiles: [],
To
setupFiles: [ './jest.setup.js' ],
N.B. the "./" prefix is required otherwise jest will state it cannot find the jest.setup.js file.
The create jest.setup.js in your project folder and add the following -
const $ = require('jquery');
global.$ = global.jQuery = $;
Node uses the CommonJS module system (https://nodejs.org/en/knowledge/getting-started/what-is-require/)
so the above syntax is required to work with Node.js

Angular (4.1.3) ng-select2 Error

I installed ng-select2 package. And I'm getting this error and code is not able to complie after 'ng serve'.
node version is 8.10.0
npm version 6.0.0
List item
OS Windows 7
ERROR in d:/PATH-TO-PROJECT-FOLDER/node_modules/#types/select2/index.d.ts (233,49): 'JQuery' only refers to a type, but is being used as a namespace here.
ERROR in D:/PATH-TO-PROJECT-FOLDER/node_modules/ng-select2/ng-select2/ng-select2.component.ts (188,18): Cannot find name 'Select2Options'.
ERROR in /src/app/pages/dashboard/dashboard.component.ts (91,19): Cannot find name 'Select2Options'.
// Dashboard component ts(91, 19) error + I've also added import to it:
public options: Select2Options;
Solutions I tried are:
As per documentation, added import and also imported in #NgModule to app.module.ts
I've jquery#3.2.1 and #types/jquery#2.0.41 installed as well.
npm cache verify, then npm cache clean --force and updated npm
deleted package-lock.json and then ran npm install
But this doesn't seem to work.
As stated in the github issue:
The interface Select2Options is removed/renamed to Options in the latest version 4.0.45
To resolve this issue, I simply downgrade the package to 4.0.44 by running
npm install # types/select2#4.0.44 --save and this worked for me.
https://github.com/NejcZdovc/ng2-select2/issues/124
I had a similar problem. I installed according to the selected2 documentation. Unfortunately, an error appeared
Error: src/app/app.module.ts:6:33 - error TS2307: Cannot find module './select2' or its corresponding type declarations.
6 import { NgSelect2Module } from './select2';
Although it was in the Initial Chunk Files
Initial Chunk Files | Names
select2.js | select2
I tried your solution but the compiler said it is not a module.
Error: src/app/app.module.ts:6:33 - error TS2306: File 'C:/Users/admin/Documents/WorkspaceAngular/medical-v0.9/node_modules/#types/select2/index.d.ts' is not a module.
6 import { NgSelect2Module } from '#types/select2',
So I installed componenet
npm i ng-select2-component --save
https://www.npmjs.com/package/ng-select2-component
It worked ;-)

Bootstrap v4 runtime/load error in Aurelia

I have the following in my aurelia.json file, among the rest of what you'd usually find. I copied it directly from the reference implementation, and as you'd therefore expect, it works fine.
{
'build': {
'bundles': [
'name': 'vendor-bundle.js'
'dependencies': [
"jquery",
{
"name": "bootstrap",
"path": "../node_modules/bootstrap/dist",
"main": "js/bootstrap.min",
"deps": ["jquery"],
"exports": "$",
"resources": [
"css/bootstrap.css"
]
}
]
]
}
}
However, I'm trying to migrate to Bootstrap 4, and it just doesn't seem to be working. In order to update the package, I've tried changing build.bundles.dependencies[].path to ../jspm_packages/github/twbs/bootstrap#4.0.0-beta as well as to ../node_modules/bootstrap-v4-dev/dist, but it doesn't change the error code or make the error manifest any less. I've also tried copying the v4 files into the dist folder for v3, which also causes the same problem.
Build is always clean; the error occurs at run-time:
DEBUG [templating] importing resources for app.html
Uncaught TypeError: plugin.load is not a function
Unhandled rejection Error: Failed loading required CSS file: bootstrap/css/bootstrap.css
EDIT:
Thanks to Ashley Grant's answer, I have updated Bootstrap through NPM, obviating any changes to aurelia.json. The error remains unchanged, which would seem to indicate a bug were it not for the fact that other people have successfully performed this migration without errors using the same toolchain.
EDIT2:
I've created steps to reproduce the bug:
$ au new
name # can be any valid value
2 # Selects TypeScript as the language
1 # Create project structure
1 # Install dependencies
cd into the project directory.
Add the two entries listed above to build.bundles[1].dependencies in aurelia_project/aurelia.json
$ npm install jquery --save
$ npm install bootstrap#^4.0.0-beta --save
Change src/app.html to the following:
<template>
<require from="bootstrap/css/bootstrap.css"></require>
</template>
Finally, execute either of the following and browse to the provided URL.
$ au run
OR
$ au build
$ serve
This yields the errors described in both Google Chrome Version 55.0.2883.87 (64-bit) and Mozilla Firefox 55.0.3 on my Arch Linux systems. I've not yet had the opportunity to test it on other systems.
Edit3:
Thanks to #vidriduch, everything appears to be working. However, if you look at the console, you find the following:
Uncaught SyntaxError: Unexpected token export
vendor-bundle.js:3927Uncaught Error: Mismatched anonymous define() module: [entirety of vendor-bundle.js printed here]
These are the two very first messages when the page loads in debug mode, but no other errors arise.
You are missing popper.js dependency for Bootstrap 4.0.0-beta.
In order for Aurelia to accept this add
"node_modules/popper.js/dist/umd/popper.js"
on the top (as per comment from #hxtk) of prepend part of aurelia.json (assuming that you are using RequireJS, otherwise have a look at webpack dependency linking for Bootstrap https://getbootstrap.com/docs/4.0/getting-started/webpack/)
Just to mention, the version of popper.js you need to install is 1.11.0 (https://github.com/twbs/bootstrap/issues/23381), so
npm install popper.js#1.11.0
or
yarn add popper.js#1.11.0
and it should work :)
Your aurelia.json configuration is correct. I'm going to guess you never ran npm install bootstrap#^4.0.0-beta --save as you are mentioning copying files in to a versioned node_modules folder, and NPM doesn't use versioned folders like JSPM does.
So run npm install bootstrap#^4.0.0-beta --save and things should start working. I have your exact configuration working in an application for one of my clients.

exception while importing module in ember js

I need to remove diacritics from string in emberjs app.
I found a plugin for this: fold-to-ascii
but I don't know how to use it in my app.
I added this plugin via npm and it is visible under node_modules folder in my app
In docs usage of this plugin is:
var foldToAscii = require("fold-to-ascii");
foldToAscii.fold("★Lorém ïpsum dölor.")
but i get an exception:
Uncaught Error: Could not find module fold-to-ascii
also tried importing it like #Kori John Roys suggested:
import foldToAscii from 'fold-to-ascii'
but it gives me only new exception:
Error while processing route: transports.index
Could not find module fold-to-ascii imported from test-ember/pods/transport/model
What am I doing wrong ?
Assuming you are using ember-cli:
npm install --save-dev ember-browserify
then you can import like this:
import foldToAscii from "npm:fold-to-ascii"

Categories

Resources