A very simple query - Loading plain old javascript file with webpack - javascript

Should be quite a common question for a webpack newbie but unfortunately couldn't find a solution -
My project uses webpack. I need to use a library but it needs to be used as the old way of adding script tag like
<script src="//messaging-public.realtime.co/js/2.1.0/ortc.js"></script>
However I am looking for some way through webpack (a loader or in some other way) such that I can use it like
import ortc from "realtime-framework"
or
import * as ortc from "realtime-framework"

You will need to either:
Install it from a package manager like npm;
Download the file locally and import it;
Or include it the normal way with a script tag, making sure it is included before your script.

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.

Reactjs - Importing CSS/JS in component

I am trying to create a webpage using a HTML theme on Reactjs. I have studied and found there are 4 ways to import CSS at this link. All these ways outputs the same way i.e <style>MY_CSS</style> just before closing HEAD tag.
This is OK for single CSS but when we are using multiple CSS it may conflict with other one.
So my question is can we import CSS so that it will show in not as <style></style>. As <style> tags works as inline CSS and I don't want to use it inline.
2nd question: How can I import Js?
As I am using requirejs to load multiple js, for this I am trying to import require.config.js where my other js are called.
Please have a look what I am getting
Need to have like this below
Please help, thanks in advance!
This is just done via ordinary ES. For example:
import React, { Component } from 'react'
import './SomeFileWithStyle.css'
The second line imports a CSS file containing, well, CSS code. You are now able to use the classes specified in there. Follow this guide if you need further help: Styling and CSS - React.
Read more about the ES import statement here: import - JavaScript | MDN
The easiest way to learn React and the way you should structure a React project ( this includes everything, from css, to multiple js files, etc ) is to use create-react-app
Let me try to elaborate a bit.
React is a javascript library. You could, for example, get the library from a cdn and include it in your index.html file much in the same way you would get jquery for example. And, with the library included, you could do things like this:
const element = React.createElement(
'h1',
null,
'Hello, world!'
);
const container = document.getElementById('root');
ReactDOM.render(element, container);
Since you have the library from a cdn, you have access to it's methods, for example createElement and the library will look for a node in the dom with id called root and insert there a h1 node containing Hello, world!. You could then apply to the newly created node a style of your choice.
This example was taken from here
While it is certainly possible to use React this way, you shouldn't, in my opinion.
What you should do is follow the steps outlined in the create-react-app link and bootstrap a project using create-react-app. This will give you a pre configured project, that will allow you to use the library in a modern way.
The project that create-react-app offers you is set up to use a tool called webpack and a tool called babel. Webpack is a module bundler. Using a set of rules, it will take several files and bundle them together. How and why it works is beyond the scope of this question. Babel is a javascript compiler or syntax transformer. Also using a set of rules, it turns ES6 into regular javascript. Again, the how and the way are out of scope. What you should know is, because of webpack and babel, you will be able to write code like this.
import styles from 'style.module.css'
This is done with no effort on your part, because everything is already configured by create-react-app.
This is why I recommend you start with this. Just install it, bootstrap a project and take a quick look at how App.js is set up. You will see there css imports, component imports and will give you a good if shallow overview of how a modern React project works.
Import your .css file from the correct path. I struggled with using <link rel="stylesheet" href="css/style.css">
in index.html without any luck.
But instead:
index.html:
<link rel="stylesheet" href="/src/css/style.css"/>
style.css:
div.custom-div {
background-color: red;
}
Now, you can use
<div className="custom-div">
You need to use css-loader when creating bundle with wepback.
Install it:
npm install css-loader --save-dev
Read more here

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';

Angular2 - require module on client side

In the context of a Node.js / Express / Angular2 / typescript (IDE=Visual Studio) app, I am trying to load a third party .js utility (packery) onto the client side (for use in a directive). Someone made typescript definitions for it. The d.ts file looks like:
declare module "packery" {
interface PackeryOptions { stuff... }
class Packery { stuff .... }
export = Packery;
}
I refer to this d.ts file, tell the browser where the .js packery script lives, and then import the module as such:
import Packery = require('packery');
This compiles without complaint. However, upon running, the browser attempts (and fails) to find "packery" at http://localhost/packery as opposed to knowing packery is an imported library. This is in contrast to the other import statements I have made on the client such as:
import {Http, HTTP_PROVIDERS} from 'angular2/http';
which work - as far as I can tell the only two pieces of information I gave it for those were also a d.ts file and the location of the .js file, just like packery. But, I must be missing something. Have tried many combinations of file locations and linking and can't get it to work. How can I get the proper linking to "packery"?
Thanks!
I found a workaround for this and thought I'd post in case it helps anyone, although I am still having difficulty with the setup posed in the original question, that is, getting statements of the type:
import foo = require('foo')
to run on the CLIENT side. These work for me in node.js on the server, but on the client, for third party libraries that have been loaded via a script tag, I cannot get it to work, even if I add mapping entries to the system.js config file, irrespective of if I point to a .js file or a d.ts file.
Anyway, what does work is if you load the library using the script tag, then in your IDE put a reference path as such at the top of the CLIENT side code
/// <reference path="foo.d.ts" />
and ensure that your d.ts file does not declare a module/namespace but rather exports methods etc. directly. This lets the IDE compile without complaint, and the client side code is able to access the third party library.
However, I'm not sure if it is preferable / best practices to do what I did or if one should be configuring System.js somehow.
Typings are empty definitions of js libraries that aren't written in a typed language. They are only useful in development for IDEs hints and stuff, in your app, you'll still use the library as you normally would, adding the js file in your index.html or w/e you load your js files from.

Is there a way to include file in coffee script?

I'd like to know if there is a way to include a file in a coffee script.
Something like #include in C or require in PHP...
If you use coffeescript with node.js (e.g. when using the commandline tool coffee) then you can use node's require() function exactly as you would for a JS-file.
Say you want to include included-file.coffee in main.coffee:
In included-file.coffee: declare and export objects you want to export
someVar = ...
exports.someVar = someVar
In main.coffee you can then say:
someVar = require('included-file.coffee').someVar
This gives you clean modularization and avoids namespace conflicts when including external code.
How about coffeescript-concat?
coffeescript-concat is a utility that preprocesses and concatenates
CoffeeScript source files.
It makes it easy to keep your CoffeeScript code in separate units and
still run them easily. You can keep your source logically separated
without the frustration of putting it all together to run or embed in
a web page. Additionally, coffeescript-concat will give you a single
sourcefile that will easily compile to a single Javascript file.
Tl;DR: Browserify, possibly with a build tool like Grunt...
Solutions review
Build tool + import pre-processor
If what you want is a single JS file to be run in the browser, I recommend using a build tool like Grunt (or Gulp, or Cake, or Mimosa, or any other) to pre-process your Coffeescript, along with an include/require/import module that will concatenate included files into your compiled output, like one of these:
Browserify: probably the rising standard and my personal favourite, lets you to use Node's exports/require API in your code, then extracts and concatenates everything required into a browser includable file. Exists for Grunt, Gulp, Mimosa and probably most others . To this day I reckon it is probably the best solution if you're after compatibility both Node and the browser (and even otherwise)
Some Rails Sprocket-like solutions like grunt-sprockets-directives or gulp-include will also work in a consistent way with CSS pre-processors (though those generally have their own importing mechanisms)
Other solutions include grunt-includes or grunt-import
Standalone import pre-processor
If you'd rather avoid the extra-complexity of a build tool, you can use Browserify stand-alone, or alternatives not based on Node's require like coffeescript-concat or Coffee-Stir
[Not recommended] Asynchronous dynamic loading (AJAX + eval)
If you're writing exclusively for the browser and don't mind, or rather really want, your script being spread across several files fetched via AJAX, you can use a myriad of tools like:
yepnope.js or Modernizr's .load based on yepnope: Please note that yepnope is now deprecated by its maintainer, who recommend using build tools and concatenation instead of remote loading
RequireJS
HeadJS
jQuery's $.getScript
Vanilla AJAX + eval
your own implementation of AMD
You can try this library I made to solve this same problem coffee-stir
its very simple.
Just type #include and the name of the file that you want to include
#include MyBaseClass.coffee
For details
http://beastjavascript.github.io/Coffee-Stir/
I found that using "gulp-concat" to merge my coffee scripts before processing them did the trick. It can be easily installed to your project with npm.
npm install gulp-concat
Then edit your gulpfile.js:
var gulp = require('gulp')
,coffee = require('gulp-coffee')
,concat = require('gulp-concat');
gulp.task('coffee', function(){
gulp.src('src/*.coffee')
.pipe(concat('app.coffee')
.pipe(coffee({bare: true}).on('error', gulp.log))
.pipe(gulp.dest('build/')
})
This is the code I used to concatenate all my coffee scripts before gulp processed it into the final build Javascript. The only issue is the files are processed in alphabetical order. You can explicitly state which file to process to achieve your own file order, but you lose the flexibility of adding dynamic .coffee files.
gulp.src(['src/file3.coffee', 'src/file1.coffee', 'src/file2.coffee'])
.pipe(concat('app.coffee'))
.pipe(coffee({bare: true}).on('error', gulp.log))
.pipe(gulp.dest('build/')
gulp-concat as of February 25th, 2015 is available at this url.
Rails uses sprockets to do this, and this syntax has been adapted to https://www.npmjs.org/package/grunt-sprockets-directives. Works well for me.

Categories

Resources