Include node_module into Ember component - javascript

I am trying to add wavesurfer to my application. I did exactly according to the instructions. at: https://www.npmjs.com/package/wavesurfer.js
After I did bower install I had wavesurfer.js folder inside my node_modules
import WaveSurfer from 'wavesurfer.js';
Theoretically WaveSurfer class should be available on my component. But after I include above code I have this error
Uncaught Error: Could not find module wavesurfer.js
at requireModule (loader.js:58)
at reify (loader.js:41)
at requireModule (loader.js:69)
at Class._extractDefaultExport (ember-resolver.js:390)
at Class.resolveOther (ember-resolver.js:122)
at Class.superWrapper [as resolveOther] (ember.debug.js:17407)
at Class.resolve (ember.debug.js:4597)
at Registry.resolve [as resolver] (ember.debug.js:4437)
at resolve (ember.debug.js:2109)
at Registry.resolve (ember.debug.js:1715)
I killed almost a week on this.
How can I make that class available for my component
Thanks

Well, open your ember-cli-build.js and import the library as follows:
// if you used npm then:
app.import('node_modules/<path-to-wavesurfer.js>');
// if you used bower then:
app.import('bower_components/<path-to-wavesurfer.js>');
depending on which package manager you used to install the dependency.
I did a quick search and found this shim: https://github.com/chrism/ember-cli-wavesurfer-js-shim, which probably includes the lib into the build. However, doesn't seem to be working with up-to-date Ember.

If you are not building your Ember app via ember-cli, you could try adding the library into your index.html file
<script src="//cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.4.0/wavesurfer.min.js"></script>
and assign it a container <div id="waveform"></div> as explained at wavesurfer-js.org

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.

Dynamically import React component from external URL and use parent React environment

I have a Main UI into which I want to load a Sub UI in the form of a React Component, which is then integrated through a React.Suspense JSX Tag. The Main and the Sub UI will both be separately bundled with Webpack. The Sub UI is bundled as a Webpack 5 Module Library.
Now, the dynamic loading of the component from an URL seems to be no problem. I can use
var path = "<< some URL to a JS-File in a CDN >>";
var SubUiComponent = React.lazy(() => import(/* webpackIgnore: true */ path));
But because the component that I want to import is bundled with Webpack, another React instance is being used. I have already tried to use Webpack Externals, but there seems to be no way that it can be used in combination with dynamic imports.
When I'm not defining externals, I get the following error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of
the body of a function component. This could happen for one of the
following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app See https://reactjs.org/warnings/invalid-hook-call-warning.html for tips
about how to debug and fix this problem.
With externals defined in webpack.config.js, I get the expected error:
Uncaught ReferenceError: React is not defined
So, is there a way of bundling a React component "kind of" as a library and then import it into another React Environment and use it there?
With two of your different local react projects, you want to link/refer/import one from another? If this is what you're trying to do then yes, it is possible.
First Approach:
You need to research on npm link
Note that package-name is taken from package.json, not from the directory name.
npm link in a package folder will create a symlink in the global folder {prefix}/lib/node_modules/<package> that links to the package where the npm link command was executed.
It will also link any bins in the package to {prefix}/bin/{name}. Note that npm link uses the global prefix (see npm prefix -g for its value).
In some other location, npm link package-name will create a symbolic link from globally-installed package-name to node_modules/ of the current folder
cd ~/projects/some-dep
npm link # Step 1.
cd ~/projects/my-app
npm link some-dep # Step 2.
now, from your my-app folder, you can install some-dep
~/projects/my-app
npm install some-dep#
Second Approach:
Bundle and publish your project to npm registry then install, import it into your other project. Refer this one that I'd published to try out
Third Approach:
Webpack ModuleFederation, when you import the project/module, it will look for it in node_modules, if not found then in the federated modules.
Ref: https://webpack.js.org/concepts/module-federation/

How to include 3rd party library that uses older import approach to Angular4.x?

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););
}

Accessing meteor application's imports directory from a package?

Meteor application directory layout:
imports/
api/
collections/
MyCollectionFile.js
packages/
mypackage/
mypackageMain.js
I can export anything from the package file and use it inside the application, that's ok. But how can I use "import" in the package, like the other way around?
// mypackageMain.js
if (Meteor.isServer) {
require ('/imports/api/collections/MyCollectionFile.js');
};
OR
import '/imports/api/collections/MyCollectionFile.js';
I tried using the path '../../imports/api/collections/MyCollectionFile.js' but it simply does not work. I can not access this file from a package.
I get the following Error for both the import and the require:
W20160618-23:25:59.486(3)? (STDERR) Error: Cannot find module '../../imports/api/collections/MyCollectionFile.js'
W20160618-23:25:59.487(3)? (STDERR) at require (packages/modules-runtime/.npm/package/node_modules/install/install.js:85:1)
Figured out that this was not possible.
However, moving the collections to a package and exporting them would make the collections available to other packages and the application.
I've also been running in to this issue and have found two solutions, both are sub-par though.
Install the thing you want to import as a npm package. $npm install --save ./imports/<the thing>.
Use npm link to create a link to the thing you want to import.
Both solutions require that you have a package.json in the directory you want to import and both won't be transpile the code and just run it against the provided version of node.
A possible solution for the transpile issue would be using a loader plugin, or somehow provide a additional configuration to System.js to tell it to transpile the code on import.

How to import $ from jQuery.min.js into Angular 2 app? name not found

I have an Angular 2 app using Typescript. I want to use jQuery's $ for a variety of tasks such as
$(document).ready(function(){ // throwing error: "[ts] Cannot find '$'. any"
console.log("loaded up!");
$("#main_div").niceScroll();
})
I have imported the jQuery.min.js file into my app via index.html like so:
<script src="app/libs/jquery.min.js"></script>
However, I have not imported anything into the app.component.ts file in regards to the jQuery code. Is it necessary, and if so, how do I import it?
import { GenericService } from './services/Generic.service'; // did not do this
import $ from './libs/jquery.min.js'; // tried this but does not work
Surprisingly, my code worked yesterday as I was developing, but not today when I ran npm start. Could anyone help me out with this import process?
Simply do a
typings install jquery --ambient --save
to install the type definition file. Remove the import $ from './libs/jquery.min.js'; and add a reference to the d.ts file at the top of your app.component.ts like so:
/// <reference path="../typings/jquery.d.ts"/>
Since you're already loading the Javascript file in your index you only need the typings for it, so TypeScript knows, that those names and methods of jQuery exist.
Just add Jquery with typings :
typings install jquery --ambient --save
Then in your index :
<script src="bower_components/jquery/dist/jquery.min.js"></script>
And normally typescript will do the job :)

Categories

Resources