Importing and using NPM package - javascript

I am trying to use a node module called "tagify" in my node.js app. In the readme file for the package (https://www.npmjs.com/package/#yaireo/tagify#installation) it says to setup as follows:
npm i #yaireo/tagify --save
// usage:
import Tagify from '#yaireo/tagify'
var tagify = new Tagify(...)
I ran the npm command and it installed fine. My EJS file has this (not shown is the input name="tags" element):
<script>
import Tagify from '#yaireo/tagify';
var input = document.querySelector('input[name=tags]'),
// init Tagify script on the above inputs
tagify = new Tagify(input);
</script>
When I load the page, I get this in the console:
Uncaught SyntaxError: Unexpected identifier (reference to 'import' line)
I'm very new to this and very confused. I've been searching the internet for two hours and can't figure out the basic task of getting this package to work. If this questions is redundant, please direct me elsewhere, because I don't know where to go.

<script src="https://cdn.jsdelivr.net/npm/#yaireo/tagify#2.9.7/dist/tagify.min.js"></script>
<script>
var input = document.querySelector('input[name=tags]'),
// init Tagify script on the above inputs
var tagify = new Tagify(input);
</script>
This code is not raw. you need to use technologies like babel or webpack to use it. easy to run this link will be enough

Related

Ruby on Rails 6 Webpack with Javascript libraries

I am building a new project in Rails 6. I have a front-end library I want to use (#tarekraafat/autocomplete.js) that is installed by yarn and exists in my node_modules directory, but is not being made available to other JS code in the browser. Here is what I have set up currently:
/package.json:
"dependencies": {
"#tarekraafat/autocomplete.js": "^8.2.1"
}
/app/javascript/packs/application.js:
import "#tarekraafat/autocomplete.js/dist/js/autoComplete.min.js"
/app/views/.../example.html.erb
<script type="text/javascript">
window.onload = () => {
new autoComplete({
[...]
});
};
</script>
I am getting an error in the browser pointing to the new autoComplete():
Uncaught ReferenceError: autoComplete is not defined
Some reading seems to indicate that I need to modify the /config/webpack/environment.js file, in which I have tried various versions of the following with no luck (including restarting the dev server):
/config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
autoComplete: 'autocomplete.js'
})
);
module.exports = environment
First, what do I need to do to add this library so it can be used correctly? Second, as someone who has not directly used webpack previously, what is the function of adding this definition to the environments.js file, and why don't I need to do it for some libraries (bootstrap, popper) but I do for others (jquery, and maybe autocomplete.js)?
In Webpacker, the usage of this library would be as follows:
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
new autoComplete(...)
// app/javascript/packs/application.js
import "../src/any_file"
This alone does not import the autoComplete variable into the global scope. To do that, the simplest thing is assign the variable to window from within your webpack dependency graph.
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
window.autoComplete = autoComplete
As an aside, you don't need to use the ProvidePlugin configuration for this library. The ProvidePlugin says: “add this import to all files in my dependency graph.” This might be helpful for something like jQuery to make legacy jQuery plugins work in webpack. It is not necessary to make your autocomplete lib work

How to fix this issue where require('./<path to json from working directory>') is throwing ERROR: Cannot find module './<path to json>'?

I am requiring the JSON file to a variable using require(./).
Here I am testing a webpage where I am using wdio test runner.
The project directory structure is like this
practiseWebdriver.io/
/test --> contains test Scripts
/pageobjects --> contains json file to be read
When tried to use:
var pageObject = require('./pageobjects/abc.json');
I am facing error -> ERROR: Cannot find module './pageobjects/abc.json'
But the script is running fine when I try :
1. var pageObject = require('/home/{user}/Documents/VS_Workspace/practiseWebdriver.io/pageobjects/abc.json');
2. var pageObject = require(process.cwd()+'./pageobjects/abc.json');
Can you please help me to identify if there's anything I am missing?
use this : require('../pageobjects/abc.json');

Getting started with unit testing JavaScript without a framework

I am building a JavaScript application (no framework yet, but I may move it to Backbone). I have created various classes, here's an example, chart.js:
var moment = require('moment');
var chart = {
...
getAllMonths: function(firstMonth, lastMonth) {
var startDate = moment(firstMonth);
var endDate = moment(lastMonth);
var monthRange = [];
while (startDate.isBefore(endDate)) {
monthRange.push(startDate.format("YYYY-MM-01"));
startDate.add(1, 'month');
}
return monthRange;
},
setMonths: function() {
// get data via ajax
this.globalOptions.months = this.getAllMonths(data['firstMonth'], data['lastMonth']);
}
};
module.exports = chart;
My file structure is as follows:
index.js
src/
chart.js
form.js
I import the two classes into index.js and use browserify to bundle these scripts up in order to use them in my web app.
Now I want to add tests for chart.js and form.js. I have added a new directory called test/ and empty test files:
index.js
src/
chart.js
form.js
test/
test_chart.js
test_form.js
My question now is what test_chart.js should look like in order to test the getAllMonths function, and what test runner I should use.
I've started experimenting with the following in test_chart.js:
console.log('hello world');
var chart = require('../src/chart');
var months = chart.getAllMonths('2014-02-01', '2015-03-01');
// assert if months.length != 14
But if I run this with node test/test_chart.js, I get errors about failed module imports for moment etc (shouldn't these be imported automatically with the original chart.js module?).
Secondly, what test runner could I use for this kind of simple testing? I'd like something that will automatically run everything in the test directory, and offers asserts etc.
I ended up using Mocha. It's really pretty easy:
npm install --save-dev mocha
mocha
Boom!
It automatically looks for files in the test/ folder.
Still having the problem with imports though.

how to require some npm modules into my js file

i have this index.jade file
include scripts
script( src='path of my site/project name/src/scripts/index.js' )
and also index.js file
var _ = require('./underscore');
var IScroll = require('iscroll/build/iscroll-probe.js');
var zepto = require('./vendor/zepto.js');
var morpheus = require('morpheus');
var easings = require('./vendor/morpheus-easings.js');
require('./vendor/zepto.touch.js');
I am getting ReferenceError: require is not defined
I want to include modules for the correct working any help ?
First :
npm install iscroll --save
Then this :
global.IScroll = require('iscroll');
The type of require you are looking to use is the node type. You can't use it directly in your browser. You need to get a bundler such as browserify or webpack, which would convert those requires to actual dependencies behind the scenes. Here's an article that would get you started with browserify.

Using NPM package on Meteor's Template

I've added the moment package using mrt add moment to format dates/times on the clientside within Meteor's templates. However I seem to be able to use it on the serverside but not within the template helpers.
How can I use momentjs within the template helpers?
server/main.js (Works!)
var moment = Meteor.require('moment');
var t = moment( '2013-11-24 16:18:06' ).format('HH:mm:ss');
console.log(t);
client/main.js (Does not work)
Template.fruits.myTime = function() {
var moment = Meteor.require('moment');
var t = moment( '2013-11-24 16:18:06' ).format('HH:mm:ss');
return t;
}
Error:
Uncaught ReferenceError: require is not defined
I tried using Npm.require('moment') which gave an error: Uncaught ReferenceError: Npm is not defined
and Meteor.require('momemt') which gave an error: Uncaught TypeError: Object #<Object> has no method 'require'
If you add moment using
mrt add moment
then it is available directly as function:
moment()
You can always find out how to use particular package by looking at its package.js file. Take a look at package.js in moment package:
...
if(api.export) {
api.export('moment');
}
...
I noticed that it is very convenient to use moment by registering global handlebars helper:
Handlebars.registerHelper('nice-date', function(date){
return moment(date).fromNow();
});
and using it directly in template:
<template name="test">
{{nice-date createdAt}} // 5 seconds ago
</template>
If you add a Meteor package, you should never need to use require(). How did you add Moment? Via the package on Atmosphere (https://atmosphere.meteor.com/package/moment) using the command mrt add moment?
Per that page, once the package is added you should see a moment global variable that you can simply call:
var oneMonentPlease = moment();
You don't need to put any require statements anywhere. The above line should just work.
Since Moment is a client-side library, you don't necessarily need to add it as a Meteor package or Npm module. You could just download http://momentjs.com/downloads/moment.min.js and save it in your /lib folder. Do that and it will automatically be available to both client and server, and the above line of code will work.

Categories

Resources