Browserify and Vue: uncaught reference error: Vue is not defined - javascript

This is my first foray into any front-end development beyond basic jQuery stuff, and I'm using Vue.js along with some other packages with Browserify. My main 'app.js' looks like this:
window.$ = window.jQuery = require('jquery');
require('bootstrap');
var moment = require('moment');
var fullCalendar = require('./vendor/fullcalendar.min.js');
var datetimepicker = require('./vendor/bootstrap-datetimepicker.min.js');
var select2 = require('./vendor/select2.min.js');
var VueResource = require('vue-resource');
var Vue = require('vue');
require('./videos/show.js');
require('./home.js');
require('./search.js');
Vue.use(VueResource);
new Vue({
el: '#search',
data: {
message: 'Hello World!'
},
});
...
It works as expected this way, but when I try to create a new Vue instance in another file (in search.js, for instance) I can't do it. I get the 'Uncaught reference error: Vue is not defined' in my console. No problem with using the other required packages elsewhere - although I don't understand why I need to import jQuery the way I'm doing it... it won't work if I do:
var $, jQuery = require('jquery');
I'm sure this is something very basic and fundamental that I am not understanding yet but any help would be greatly appreciated!

The problem you are having is the basics of using modules. In general, a module should always export some behavior or property and then you require that module and use it. For example, say I wanted to add a hidden into to a form on some pages. I would do this:
AddSecretToken.js
module.exports = function(form) {
// code here to add the hidden input to the passed in form
}
Then somewhere else where I had a form that needed the secret input, I would require it:
MyForm.js
var addSecretToken = require('./AddSecretToken');
...
// some code that makes a form
addSecretToken(myForm);
...
Obviously, at some point you need some code that actually runs something but that would be your root module or the page where you require the root module. So maybe you have an app.js at the top and it requires what it needs and then runs app() without exporting anything. That makes sense. But the majority of modules shouldn't be doing that.
Any time you need some behavior, you should make a module and then anywhere you need the behavior, you require the module. Each module should require what it depends on -- it shouldn't depend on any global (sometimes jQuery is an exception).

Related

Rails, webpacker: where/when to use the import statement in classes, and what's the purpose of requiring in the pack/application.js?

I'm upgrading an older application to Rails 6, which uses webpacker for all the JS asset management.
I'm using the pikaday calendar library, and have added it via yarn add pikaday, verified it shows up in packages.json and then added it to my app/javascript/packs/application.js via require("pikaday").
I have a JS class called Datepicker that I'm using to abstract the actual pikaday calendar. I'm doing this because I may someday change the datepicker implementation, and this way I'll only have to change a single class instead of update all my pikaday calls.
However, it doesn't seem to matter if I require("pikaday") in the application.js pack file or not; as long as I import Pikaday from "pikaday" in the class I'm referencing it in, it makes no difference.
Questions
I'm trying to gain understanding of what's going on.
Do I need to add require("pikaday") or import Pikaday from "pikaday" in the app/javascript/pack/application.js file? Why or why not?
I'm familiar with the principle that globals are bad and should be avoided, but is there a way to avoid having to import CLASS from "class_file" on every JS file that references it? In my example I want to use the Datepicker class in multiple places. The reason I ask is because I have 10+ classes like this, and it's a little annoying to have 10+ import statements at the top of every JS file that I want to use these in. There are certain classes that I always want access to. I've played with the webpacker ProvidePlugin functionality, but it complains that Datepicker is not a constructor, so I'm probably missing something but I don't have enough knowledge to know what.
app/javascript/custom/datepicker.js
import Pikaday from "pikaday"
export default class Datepicker {
constructor(element, options) {
if (options == null) { options = {} }
// Store DOM element for reference
this.element = element
// Do not re-run on elements that already have datepickers
if (this.element.datepicker === undefined) {
options = Object.assign({},
this.defaultOptions(),
options
)
const picker = new Pikaday(options)
// Store picker on element for reference
this.element.datepicker = picker
return picker
} else {
console.log("Datepicker already attached")
return
}
}
// Overridden by `options` in constructor
defaultOptions() {
return {
field: this.element,
format: "M/D/YYYY",
bound: true,
keyboardInput: false,
showDaysInNextAndPreviousMonths: true
}
}
}
app/javascript/packs/application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("moment")
// Note: if using `#rails/ujs`, you do not need to use `jquery-ujs`.
import "jquery"
// Does not matter if I require this or not, as long as it is imported in the
// class file, I can remove this require statement and everything still works.
require("pikaday")
// StimulusJS
// Webpack's `require` looks for `controllers/index.js` by default
require("controllers")
require("custom/datepicker")
You asked a couple questions:
You only need import Pikaday from 'pikaday' in the file where you reference the imported variable, Pikaday. In this case, you only need this import in your custom datepicker module. You can remove require("pikaday") from your application.js pack file.
The reason for this is Webpack will take your application.js pack as an entry point to a dependency graph; starting there, it will recursively traverse each required/imported module, find the dependencies of those modules, and so on, until all declared modules are included in the bundle. Since you have declared import 'custom/datepicker' in the application.js pack, and the custom datepicker imports pikaday, it will get included in the bundle as dependency.
Your custom Datepicker gets compiled as an ES module (rather, Webpack's implementation of ES module), since you are using the ES module syntax export default .... This is important to the way ProvidePlugin works. From the Webpack 4 documentation of ProvidePlugin:
For importing the default export of an ES2015 module, you have to specify the default property of module.
This means your Webpack configuration for the plugin entry for Datepicker would look something like this (using the Rails Webpacker environment api):
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
const {resolve} = require('path');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
Datepicker: [resolve('app/javascript/custom/datepicker'), 'default']
}))
module.exports = environment
Opinion: That said, I encourage you to make your imports explicit, e.g. import Datepicker from 'custom/datepicker' in each module where Datepicker is referenced. Even if repetitive, it will become much easier to integrate with tools like ESlint, which, with certain code editors, can provide inline feedback about errors from compilation—much easier to setup with explicit dependencies declared in each module.
I put together a working demo of Pikaday using your custom Datepicker with the ProvidePlugin here: https://github.com/rossta/rails6-webpacker-demo/commit/be3d20107c2b19baa8b9560bce05e0559f90086d

How to use an external non vue script in vue

I try to use an external script (https://libs.crefopay.de/3.0/secure-fields.js) which is not vue based
I added the script via -tags into index.html
But when I try to intsanciate an object, like in the excample of the script publisher.
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
Vue says "'SecureFieldsClient' is not defined"
If I use this.
let secureFieldsClientInstance =
new this.SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
secureFieldsClientInstance.registerPayment()
Vue says: Error in v-on handler: "TypeError: this.SecureFieldsClient is not a constructor"
My Code:
methods: {
startPayment () {
this.state = null
if (!this.selected) {
this.state = false
this.msg = 'Bitte Zahlungsweise auswählen.'
} else {
localStorage.payment = this.selected
let configuration = {
url: 'https://sandbox.crefopay.de/secureFields/',
placeholders: {
}
}
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
secureFieldsClientInstance.registerPayment()
// this.$router.replace({ name: 'payment' })
}
}
}
Where is my mistake?
EDIT:
Updated the hole question
Here is a minimal Vue app for the context your provided, which works:
https://codepen.io/krukid/pen/voxqPj
Without additional details it's hard to say what your specific problem is, but most probably the library gets loaded after your method executes, so window.SecureFieldsClient is expectedly not yet defined. Or, there is some runtime error that crashes your script and prevents your method from executing. There could be some other more exotic issues, but lacking a broader context I can only speculate.
To ensure your library loads before running any code from it, you should attach an onload listener to your external script:
mounted () {
let crefPayApi = document.createElement('script')
crefPayApi.onload = () => this.startPayment()
crefPayApi.setAttribute('src', 'https://libs.crefopay.de/3.0/secure-fields.js')
document.head.appendChild(crefPayApi)
},
I found the solution.
the import was never the problem.
I had just to ignore VUEs/eslints complaining about the missing "this" via // eslint-disable-next-line and it works.
So external fuctions/opbjects should be called without "this" it seems.
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
You could download the script and then use the import directive to load the script via webpack. You probably have something like import Vue from 'vue'; in your project. This just imports vue from your node modules.
It's the exact same thing for other external scripts, just use a relative path. When using Vue-CLI, you can do import i18n from './i18n';, where the src folder would contain a i18n.js
If you really want to use a CDN, you can add it like you normally would and then add it to the externals: https://webpack.js.org/configuration/externals/#externals to make it accessible from within webpack

How to import jQuery into a jQuery plugin in Angular 2+ / Webpack / Angular CLI

I'm trying to import a jQuery plugin into a single Angular component. It runs in every other browser, but IE 11 chokes on it:
SCRIPT1002: Syntax error
main.bundle.js (1376,1)
When I click the error, it shows me the line at issue:
eval("Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(\"../../../../jquery/dist/jquery.js\");\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(\"../../../core/esm5/core.js\");\n// require('jquery');\n\n\n\n/*\ndjaodjin-annotate.js...
That's not all of it, but it appears to be to do with importing jQuery, and indeed, when I remove the jQuery import, it runs fine.
The issue may be that I'm importing jQuery into a JavaScript (.js) file, which is a jQuery plugin. Here's a simplified version of it:
import * as jQuery from 'jquery';
(function($) {
'use strict';
function Annotate(el, options) {
this.init();
}
Annotate.prototype = {
init: function() {
console.log('It\'s working.');
},
};
$.fn['annotate'] = function() {
const annotate = new Annotate($(this));
return annotate;
};
})(jQuery);
If I can't import jQuery into a jQuery plugin, how can I use a jQuery plugin? Is there a way around this?
BTW, I'm using jQuery only in one component. The rest of the application is clean of it.
I'd say you don't need to import jQuery in your plugin; your plugin should just assume that jquery has been included and fail if it has not
You can include jquery (first) then your plugin file into your project. Then in your component just declare jquery
declare let $ : any;
and instantiate your plugin like
$('div').annotate();
I actually found that my jQuery plugin had errors in it. It had a couple of lines with ES6 syntax that IE didn't like. But when Webpack compiles it, it turns the whole thing into a string, all on one line. At runtime, it then runs eval() on the string. So you don't get valuable error messages with line numbers. It just gives you the stupid error that I got. But I think #David has a good point. We maybe don't need to import jQuery.

How can I make add firepad to my reactjs project?

So I've been learning react, and wanted to make a basic firepad instance. My current setup is having one container div in my index.html, and having all of my react components rendering through that div. My current attempts and the code I'm showing with this have been in an environment with gulp and browserify, but I'm also playing around with ES6 and webpack. So I'm pretty flexible about getting this working as I learn. Here's the code:
"use strict"
var React = require('react')
, Firebase = require('firebase')
, fbRoot = 'myURL'
, CodeMirror = require('codemirror')
, Firepad = require('firepad')
, firepadRef = new Firebase(fbRoot + 'session/')
, myCodeMirror = CodeMirror(document.getElementById('firepad'), {lineWrapping: true})
, myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, { richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});
var WritePage = React.createClass({
render: function(){
return (
<div>
<div id="firepad"></div>
</div>
);
}
});
module.exports = WritePage;
The first error I was getting was that it couldn't find the codemirror.js file. Although CodeMirror was being correctly defined in Chrome's dev tools, I moved that from requiring the npm package to just linking the 2 needed codemirror files to my html. It then gave me an error about not being able to take .replaceChild of undefined. I then tried moving all of the dependency files over to my index.html, but still had the same .replaceChild error. Anyone have any experience with react and firepad? I read in the reactfire docs that it's one way binding from firebase to my site, which for my case making a read-only firepad would be fine. Like I said, I'm flexible all of this stuff is new to me.
From the link that Michael provided.
The problem is that you are trying to reference a DOM element before React has rendered your component.
, myCodeMirror = CodeMirror(document.getElementById('firepad'),{lineWrapping: true})
, myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, {richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});
By moving this code into componentDidMount(), it runs after the CodeMirror DOM element has been constructed and you'll be able to reference the DOM node. You will also probably find it easier to use the React ref attribute instead of document.getElementById().
Use these npm packages - brace, react-ace, firebase, firepad.
Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad
import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';
Use ref to get instance of ReactAce and initialize it in componentDidMount using:
new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);
Similarly for CodeMirror editor.
Hoping, this would be of some help.

TypeScript: Handling import from external libraries

I just started using Famo.us and wanted to use it as an opportunity to learn typescript at the same time to leverage on its awesomeness. So I did the following
Used yo famous to create the Famo.us project as per the documentation
I was not sure how to include typescript so I created a typeScriptHTML project, copies the .csproj file over and manually edited it. I tried using the NVTS and specified that it should create it from an existing folder but I always got an error saying that the file path was too long. It checked and some of the modules have very long path. Couldn't even delete them and the system was saying the same thing. In the end I discarded the idea and used the typescript html application. It generated no errors.
I added a file app.ts, wrote some sample code in it and it generated the js file as expected.
Now I wanted to translate main.js to main.ts and I'm stuck with the following issues
i. var Engine = require('famous/core/Engine'); gives the error could not find symbol 'require'.
ii. import Engine = require('famous/core/Engine') gives the error: Unable to resolve external module "famous/core/Engine". Changing the path to "../lib/famous/core/Engine" gives a similar error with a different file name.
iii. Created a file Famous.d.ts but I don't think I'm getting it I'm not doing something right
declare module "famous/core/Engine" {
class Engine{
public createContext(): Engine
}
export = Engine
}
In the end, my confusion is how to I translate the sample code to typescript:
/*globals define*/
define(function(require, exports, module) {
'use strict';
///first
var Engine = require('famous/core/Engine');
var DeviceView = require('./DeviceView');
var mainContext = Engine.createContext();
var device;
createDevice();
function createDevice() {
var deviceOptions = {
type: 'iphone',
height: window.innerHeight - 100
};
device = new DeviceView(deviceOptions);
mainContext.add(device);
}
});
Any assistance appreciated.
It turned out to be a lot easier than I thought. One way was to declare the class and export it as a module
declare class Engine{
...
}
export module 'famous/core/Engine'{ export = Engine; }
Manage to get a tiny definition of famous running using this.

Categories

Resources