I have setup browserify with Gulp.
When I require jQuery, everything works:
var $ = require('jquery');
When I try to require jquery load template module
var loadTemplate = require('jquery.loadtemplate')
I get an error
module "jquery.loadtemplate " not found
I installed loadtemplate using npm like this
npm install --save jquery.loadtemplate
I think there is an error in the package.json of the jquery.loadtemplate module. It should define the source of the plugin somewhere and it's missing. In other modules the source is defined in the "main" property. It should say something like
"main": "jquery-loadTemplate/jquery.loadTemplate-1.5.0.js",
depending on the location of the script file. You can change it manually, but then it'll be deleted the next time you update/reinstall your npm package.
Related
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
I have a package in my dependencies in package.json of npm. I have included the package from github in following way-
"dependencies": {
"#aeternity/aepp-components": "git+https://git#github.com/aeternity/aepp-components.git#feature/v3",`
}
When I run npm install, everything installs, and I can see the module in node_modules folder. However when I try to import, and run, npm gives an error saying
dependancy not found
To install it, you can run: npm install --save aepp-components
What am i doing wrong here?
Edit: Snippet I used to import:
import AeButton from 'aepp-components'
You need to do
import { AeButton } from '#aeternity/aepp-components'
see that how AeButton is imported using destructuring. And #aeternity specifies the default root source for the files and helps you map your file imports to it. Use that and it will work. You can also have a look at here in the doc
When you have #something/package-name, this is the name of the entire package, you have to import using this full name. Now, why?
This is called a scoped package, and #something is the scope of that package. You can check more about scoped packages here.
Some packages exports items/components/whatever inside an object, which requires you to use the destructuring method. You can only be sure how it is imported if you look at the docs, otherwise you would need to deep into the codebase.
I'm working on a Symfony 3 project and trying to build a skeleton fỏ frontend development. I decided to use webpack encore.
This is my webpack entry file:
// assets/js/app.js
// loads the jquery package from node_modules
var $ = require('jquery');
require('node-waves');
require('popper.js');
require('bootstrap');
require('mdbootstrap');
require('slick-carousel');
require('jquery-validation');
require('jquery-validation-unobtrusive');
require('multi-step-form-js');
$(document).ready(function() {});
The things seem okay if I don't use the "multi-step-form-js". If I require it into the entry file. I will get an error like this in console of Google Chrome "Uncaught TypeError: Cannot read property 'prototype' of undefined". It locates me to this snippet of code inside the libary:
$.validator.prototype.subset = function(container) {
var ok = true;
var self = this;
$(container).find(':input').each(function() {
if (!self.element($(this))) ok = false;
});
return ok;
};
I think the problem is missing of dependence (the "jquery-validation"). I tried to require it with this line of code "require('jquery-validation');". The problem isn't be solved. I guess that webpack use requirejs by by default so I have to find a special way to require it. Unluckily, I'm still finding.
Are there any ideas about how to solve it?
Thanks in advance!
For missing dependencies, you can try installing it manually into your devDependencies with the following.
npm install -D jquery-validation or yarn add -D jquery-validation
Please ensure that the package name is correct. I am just using what you have spelt.
What is the proper workflow to include the library to angular 4.0 and use it inside a component?
My steps:
yarn add mathjs
Then there should be a way to injects js libraries in one of the build lifecycles so the angular4 component can use it. JHipster utilizes Webpack and Yarn.
Then I tried to add to Component (docs):
import { mathjs } from "./mathjs";
and
var math = require('mathjs');
Those were not working. What am I missing?
UPDATE:
It seems like mathjs uses older approach suggesting var math = require('mathjs'). Maybe it is similar to JQuery question in some way...
UPDATE2
This is a great question and I'm glad you ask because I wish I had what I'm about to write the first time I encountered this little problem. This is a typescript/javascript and webpack issue before it is an angular issue. I definitely am planning a writeup on my blog soon as possible.
Your Scenario:
You run
npm install mathjs
Now you try to use math.js from a component:
Find math.js dist js file (node_modules/mathjs/dist/math.js) and reference like this
import {mathjs} from "../../node_modules/mathjs/dist/math";
But you get error message saying "set --allowJS". You do that like this:
Set --allowJS in config (tsconfig.json)
{ "compilerOptions": {
"allowJs": true, ...
Now you get:
ERROR in ../node_modules/mathjs/dist/math.js (12209,13): Unreachable
code detected.
Looking in the math.js source, you see that it is an old school module but there is no root wrapper function (one function to bring them all and in the darkness bind them..) (more on that later).
Solution: install a typings file for the target lib (#types/mathjs)
First, check to see if you can get #typings files for your module here
https://microsoft.github.io/TypeSearch/
Grab mathjs typings file from npm (https://www.npmjs.com/package/#types/mathjs) and Run npm install to add the typings .d.ts files to the target lib's node_modules directory
npm install --save #types/mathjs
Add your type ref correctly
import * as mjs from "mathjs"
Use it like this:
console.log("e was: " + mjs.e);
I have the complete solution for the math.js lib on my github here
https://github.com/res63661/importOldJSDemoWithTypings/
More:
For examples look no further than your own angular project. CLI creates node_modules folder each time you run npm install after creating a new project with ng new . Dig down into here and note the d.ts files for many of the .js files.
When messing with typings or defining your own (.d.ts files) be sure to restart your server between builds as the typings don't seem to update currently on the fly
Further reading:
http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html
https://angular.io/guide/typescript-configuration#typescript-typings
https://microsoft.github.io/TypeSearch/
Lastly:
If you are in a pinch and this is not working for you, I did have success creating a custom wrapper for a different (much smaller) module by wrapping it in a master export type
export var moduleNamer = (function(){
//module implementation
}());
then dumping the .js file local to my component and then referencing it as follows:
//reference like this from your component:
import {moduleNamer} from "./source"; //from source.js
--rich
I did this way and it worked for angular9.
First install npm package mathjs.
npm install mathjs
Then import in your component or directive.
import { round } from 'mathjs'
You may test with this.
console.log(round(math.pi, 3) )
Try to include the script into index.html:
<script src="./assets/math.js" type="text/javascript"></script>
Then add this into your component file:
declare const math;
You can then use math in your component:
ngOnInit(): void {
console.log(math.sqrt(-4););
}
Instead of adding <script src="https://checkout.stripe.com/checkout.js"></script> in the Index.html is it possible to add somehow URL for this JS-file in the package.json file (it is simple JS-file, not NPM package; and it is just URL for this JS-file, not GitHub URL) to NPM download and install it? The reason for it - there is a Webpack config which make some processing of all used JS-files. May be it is better to include all external JS-files (not NPM packages) into this Webpack processing
If you are already using Webpack you may consider using something like little-loader.
npm i little-loader --save
And then in your code
var load = require("little-loader");
load("https://checkout.stripe.com/checkout.js", function (err) {
// ... your code ...
});
You can get some more inspiration from other answers as well.
In the Webpack issues I see the maintainer suggesting this approach:
var $script = require("scriptjs");
$script("https://checkout.stripe.com/checkout.js", function() {
//.... your code ...
});
But that package looks a bit unmaintained.
At the end of the day, an option to consider is to just leave it in the HTML as well, it's not necessarily a bad thing.