How to use this JS library in Laravel? Import? Require? - javascript

I'm very sorry for asking such a beginner question, but I just learned the basics of JS without and do not completely understand the new ES6-features.
I just want to use rangy within my project and initialize the rangy object within <script></script>-Tags in my html-file (Blade-template) with the following method
rangy.init();
The rangy-library consists of six files, all of whom I included into my footer.
Chrome console tells me that rangy is undefined. What do I need to do?
I tried thousands of syntactical variants of import but the console tells me unexpected token import
I tried compiling the files down to one file with Laravel mix (mix.babel, mix.js, mix.scripts), nothing worked.
I'm pretty sure I just need to grasp the concept of how to work with ES6-Modules but not tutorial really helped. Maybe one of you can help me to figure out how to use rangy in this particular case?
Thanks in advance!

You should use the import syntax to import modules with JavaScript as this is the supported syntax which will eventually work in browsers. However, because browsers are not yet supporting this feature it means you need to enable webpack to use babel-loader.
Once that configuration is setup and working you can simply import your module like this...
import rangy from 'rangy'
Of course you also need rangy to be available either locally in your node_modules folder or installed globally so webpack and babel will know where to find it.

Thanks for your answers. I tried a few things and didn't really succeed...
So I did the following: In my webpack.mix.js (Laravel Mix) I have the files that I need:
mix.babel([
'node_modules/rangy/lib/rangy-core.js',
'node_modules/rangy/lib/rangy-classapplier.js',
], 'public/js/rangy.js');
I embed the compiled rangy.js in my footer element
<script type="text/javascript" src="{{ URL::asset('js/rangy.js')}}"></script>
Below I import and initialize rangy
<script>
import rangy from 'rangy';
rangy.init();
</script>
And chrome console gives me Uncaught SyntaxError: Unexpected token import.
Was that the wrong approach?

Related

How to use npm packages as ES6 modules loaded by the browser in 2021?

I'm a JavaScript beginner. I do not use a "bundler".
For a few days now I've been trying to use moment.js and other date-time libraries in some JavaScript by importing it using ES6 modules (ESM).
I have a JS module I wrote, which is transpiled from TS, and that has this line:
import moment from "../lib/moment/src/moment.js"
My module is itself loaded via an import from a <script type="module" > tag, which works.
I've discovered that the moment package contains what looks like "source" code in its src folder which seems to look more like the JS/TS I'm accustomed to, and has a "default export" at the bottom.
So I'm referencing that "source" version in my transpiled JS module. This gets me past a couple of errors I was getting:
The requested module 'blah' does not provide an export named 'default'
And
Cannot set property 'moment' of undefined (at moment.js:10)
And leaves me stuck with loading the other modules its dependent upon, because I guess, their file extensions are missing.
GET https://blah/lib/moment/src/lib/locale/locale net::ERR_ABORTED 404 (moment.js:37)
After 3 days tearing my hair out I feel like I have been fighting a battle I shouldn't be attempting at all.
I would expect in 2021, what with widespread ESM browser support, that this would just work, but I've tried 5 different date-time libraries and had no success.
I assume the 404s have occurred because the moment authors are NOT expecting people to be using their library like this, so they left off the file extensions knowing full well that it wouldn't load in a browser??
Am I supposed to add an extra step in my client-side build process, Gulp, to add the extensions back on in the moment source code??
Or am I doing something else wrong?
Is it perhaps that everyone uses a "bundler" and these tools fix all this stuff somehow and so these issues never arise for 99% of web devs??
Thanks in advance.
You want to import a bundled version of the lib to be able to do that. Try:
import from 'https://unpkg.com/moment#2.29.1/dist/moment.js' ;
You can download the bundled version and add to your project. Don't forget to put the license as well and check if they are at least MIT or similar.
If you want to refer to the source code you will certainly need to build that. Specifically with libs that are using typescript.

import/export modules from packages like tippyjs in browsers using only JavaScript ES6

Is it possible to import, using only JavaScript ES6, modules from package like tippyjs (https://github.com/atomiks/tippyjs)?
I tried to locally install the package via npm and use the files like this:
import tippy from '../node_modules/tippy.js/dist/tippy.esm.js';
but the browser give me this error:
validation.ts:46 Uncaught ReferenceError: process is not defined
I have also tried, unsuccessfully, to "replicate" what the CDN is doing.
Thanks to what magic does the CDN work?
<script src="https://unpkg.com/#popperjs/core#2"></script>
<script src="https://unpkg.com/tippy.js#6"></script>
I know I am supposed to use CDNs, CDNs are great ecc., but I just want to have a single js module file in my HTML where all the import of my local files are:
<script type="module" src="js/modules.js"></script>
Can't rely only on CDNs.
What I am missing?
Please note that I'm not usign node.js, is just an html page and some JavaScript.
I don't think this can work with ES6 modules in the browser because of the way that tippy.js references popper. It uses the syntax import { createPopper, applyStyles } from '#popperjs/core'; which the browser can't understand. There's an issue about this on Github with regard to bootstrap, which has the same problem apparently.
I don't get the error you're getting by the way, I get the one in the issue. My HTML file is as below with tippy.js installed in the same folder:
<body>
<button id="myButton">My Button</button>
<script type="module">
import tippy from '../node_modules/tippy.js/dist/tippy.esm.js';
tippy('#myButton', {
content: 'Tooltip!',
});
</script>
</body>
Running this gives error:
Uncaught TypeError: Failed to resolve module specifier "#popperjs/core". Relative references must start with either "/", "./", or "../".
I don't think you can edit the import in tippy.js locally to fix this, either: popper's own imports then fail to work for me.
The workaround, as an answer to the issue says, is to use a module bundler like webpack if you want to create a .js file you can reference. This also begs the question of what the point is of an esm install if it can only be used from node.

How to configure TypeScript to throw an error/warning for incorrect import statement?

I am working on converting a large application from JavaScript (Backbone and Angular 1) to TypeScript. When we convert a file that is used by other files we understand that we have to update the import statements in those other JavaScript files so that it imports the new TypeScript file correctly. Our syntax update in fake-file.js is as follows.
Before:
import OurService from 'our.service';
After:
import { OurService } from 'our.service';
I understand that this is an easy change but TypeScript is new to many developers and there have been problems with people missing some of these import statements or forgetting to change them all together resulting in some issues during runtime. I have looked into compiler options but I do not see any that would fix this issue but I could be misinterpreting them.
Question: Is there a way to configure the compiler (or a Visual Studio Code plugin) to throw a warning or an error to prevent this from happening?
I assume that I understood your requirement and possibly you need to adapt a linting process and consequently I would suggest the following tools (which I also use in my project):
Airbnb Javascript style guide (your import statement concern-https://github.com/airbnb/javascript#modules). These are a well-defined set of standards defined for any JS application (including ES).
ESLint. You can run ESLint from the terminal and configure it for your project that highlights warning/errors in your code. If this looks complicated, you can generate the tslint document for your entire project in the website itself. Click on rules configuration and configure the ES rules for your project. There are some import related rules too.
PS: Feel free to add your comments.

importing functions - NodeJS - non-html

I am learning automation for work and currently a little stuck. So far stackoverflow has been a life saver :)
I am writing a test for selenium in visualstudio in javascript (nodes). I understand this is not a great combination but thats what work wants.
I have a test in the app.js file (see screenshot). It references a function in the functions.js file. I cannot get it to recognise the function though. I presume I need to reference the files containing the function. I have tried import 'import cellFromXLS from "functions.js";' and it does not work(Unexpected token import error).
Any ideas on what I can do? Anything fancy like modifying the package.json file to include all files with functions in them?
I am on the latest node.js and the latest drivers.
Also it seems intellisense does not work for javascript in visual studio. Is this right or anyway to fix it?
VisualStudio screenshot
Node doesn't support import natively just yet.
In your functions file you can do something like
function blah(){
console.log("I am blah")
}
function wah(){
console.log("Wah wah")
}
module.exports = {
blah,
wah
}
then in app.js you can do:
const functions = require('./functions.js')
functions.blah()
functions.wah()
The error already tells you what's wrong.
You need to use
const cellFromXLS = require("./functions.js");
instead of
import cellFromXLS from "functions.js"
if you want to use the import syntax, check out Babel

How to include external Javascript library in an Ionic 2 TypeScript project?

I build an Ionic Project using Ionic 2, Angular 2 and TypeScript to test the framework a bit. I need to include an external library (ntc.js) to my project, since I need it to name hex colors.
I know including a Javascript library to TypeScript should work, since whatever works in JS works in TS. I just don't want to include it the wrong way.
I tried to add the library to www/build/js, but it doesn't seem to work and it doesn't seem like the good way to do this. I tried to search for ways to do this but found nothing (might be because Angular 2 and Ionic 2 is still fresh).
Things like :
import * as ntc from '../../js/ntc';
doesn't seem to work as well, even if my library is located at the right place. TypeScript doesn't seem to read my file properly, if it reads it at all.
What is the good way to do this? Where should I place my .js file in my project directory?
You import it by adding it to your index.html like any other regular javascript file.
Then in your ts file you do:
declare var Tree:any;
Then in your code, you can use the Tree variable, albeit it exists in the Javascript file. this line of code is basically telling the typescript compiler there is a variable out there Tree which it should ignore.
Besides doing a declare var which tells ts that the variable exists you can use typings of typescript.
By writing
typings install libraryname
In your console you get a file that already has declare var/class and you can see all of its functions/properties when you import it.
import {lib} from 'libraryname';

Categories

Resources