Vuejs 2 + laravel elixir + lodash Uncaught ReferenceError: _ is not defined - laravel-5

I'm using the tools specified in the title. I import lodash in my bootstrap.js
window._ = require('lodash');
However, when I try to use something like this (similar example to here), I get the error discribed in the title
created() {
this.test();
},
methods: {
test: _.debounce(function () {
console.log('calculating', true);
setTimeout(function () {
console.log('calculating', false);
}.bind(this), 1000)
}, 500),
}
However, if I remove the window._ = require('lodash'); and insert lodash manually in the page it works fine, like
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
What I'm missing?
Also, What is the advantage of importing the libraries by require instead of using Gulp to merge and uglyfy everything?

I am not sure why you are getting that error related to _.
On your other question, I can think following advantage of using require over gulp or any other build tool:
All build tools comes with their own set of dependencies and other accessories, which bloats your overall code size.
You may start to rely on their plugins and time can come, when you need to use grunt for one task, while for other tasks you are using grunt, quting from gulp-grunt
What if your favorite grunt plugin isn't available for gulp yet? Don't fret, there is nothing to worry about! Why don't you just hook in your grunt configuration?
You will have to manage updating of different plugins of gulp and make sure all are working with new updated versions.
These are some of the things I have experienced or read about, but these tools do remove the pain of building, hot-reloading, compressing or obfuscating your code, but definetely there can be other raw way to do these, as what these are doing is providing you an abstraction.

Related

Laravel, Datatable, Composer and Webpack : Good practices to allow developpers to customize my library in their projects

To set the context I am creating a CRUD application for Laravel. It is installed via composer and the sources are therefore in the vendor/organization/package directory.
In my project, I use Datatable. So I use Laravel Mix to compile my sources and a command line allows to copy JS and CSS compiled files into the public directory of the Laravel Host application.
I would like however that the developers who will use my library can customize the display of some Datatable cells. To do this you must use Datatable's createdCell configuration.
$('#example').dataTable( {
"columnDefs": [ {
"targets": 3,
"createdCell": function (td, cellData, rowData, row, col) {
if ( cellData < 1 ) {
$(td).css('color', 'red')
}
}
} ]
});
The problem is that the JS sources of my project are already compiled...
For the moment I found a temporary solution that consists in leaving the JS sources in vendor/organization/package but copying the webpack.mix.js configuration into the Host application and asking the developers to compile themselves. The problem is that all JS dependencies must also be installed and it doesn't take very seriously to force the developers to compile sources before being able to use my library.
What are good practices to achieve this objective?
The following source may help, but I confess I don't know how to apply it to Laravel:
How to bundle vendor scripts separately and require them as needed with Webpack?
Thank you for your help.

How do I keep the packager from trying to include a file that doesn't exist?

I am trying to use socket.io-client in my React app and am running into an odd problem. Deep inside engine.io (required by socket.io-client) there is a file called websocket.js with the following bit of code:
if (typeof window === 'undefined') {
try {
NodeWebSocket = require('ws');
} catch (e) { }
}
Since window is not undefined, you might think that this code does nothing, but you’d be wrong.
My packager (the standard React Native packager, so far as I know) goes through all the Javascript files and looks for all the import and require commands, and packages up the files they refer to.
The ws module contains a file called WebSocket.js, which intended for Node.js and makes use of Node.js modules like url.js and http.js, which of course do not exist in React, so the attempt at packaging fails.
Deleting those five lines fixed the problem and everything worked, but there must be a better way. Can I tell the packager to exclude certain modules?
I wasn't able to reproduce your problem, but you can try to blacklist the ws package.
How to blacklist specific node_modules of my package's dependencies in react-native's packager?
You can try the below code :
if (typeof window === 'undefined') {
try {
var wsNode = 'ws' // store node module name in a string
NodeWebSocket = require(wsNode); // dynamic require will exclude the node module to get bundled in react-native
} catch (e) { }
}
I haven't solve my problem as posed, but I figured out what was going on, why I was having difficulties other users were not.
In the file node_modules/engine.io-client/package.json was the following entry:
"browser": {
"ws": false,
"xmlhttprequest-ssl": "./lib/xmlhttprequest.js"
},
My venerable version of the React packager did not understand the "false" to mean "skip including ws [WebSockets] when you are building for the client side". Upgrading the packager made the problem go away.

Jasmine Ajax request.respondWith is not working

I am using Jasmine 2.0.4 with jasmine-ajax 2.99.0 to try to test a module that calls a web service.
The code is the following:
define(['models/data-service', 'models/admin', 'models/contest', 'models/participant', 'ContestResponse'],
function(dataService, admin, Contest, Participant, ContestResponse){
"use strict";
describe("Data Service Tests", function(){
var onSuccess, onFailure, request;
describe("on new contests loaded", function(){
beforeEach(function(){
jasmine.Ajax.install();
});
it("calls onSuccess with an array of Contests", function(){
onSuccess = jasmine.createSpy('onSuccess');
onFailure = jasmine.createSpy('onFailure');
dataService.getContests()
.done(onSuccess)
.fail(onFailure);
request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('/api/contest');
expect(request.method).toBe('GET');
request.respondWith(ContestResponse.getResponse().contest.success);
expect(onSuccess).toHaveBeenCalled();
var successArgs = onSuccess.calls.mostRecent().args[0];
expect(successArgs.length).toEqual(4);
});
});
});
});
Everything works until it reaches the line where I try to call the respondWith method of the request. Even though I can see that the object returned from the jasmine.Ajax.requests.mostRecent() is of type FakeXMLHttpRequest, respondWidth is marked as undefined. Any Ideas?
Thanks
[UPDATE]
I have been able to narrow it down. It looks like the mock-ajax.js file is not being loaded. I have the karma-jasmine-ajax node module installed and have added jasmine-ajax to the frameworks array of the karma.conf.js like this:
frameworks: ['jasmine-ajax','jasmine', 'requirejs'],
is there anything else I need to do?
[RANT] no wonder why so few developers are running unit test with javascript [/RANT]
I faced the same issue, it looks like the latest version doesn't have respondWith method.
Downgrading the jasmine-ajax plugin made the trick:
npm install karma-jasmine-ajax#0.1.1
Now I can see respondWith is working fine.
This appears to have been a transitional problem in one of the jasmine-ajax libraries. Upgrading to latest version (3.1.0 at the time of this writing) will fix your problem.
npm install jasmine-ajax
bower install jasmine-ajax
or
jasmine-ajax on github
If you can't change jasmine-ajax versions due to conflicts (ie: you use Jasmine 1.3 or something else that has a dependency on a different version of jasmine-ajax), you can use: request.response instead of request.respondWith

Simple RequireJS in node

I would like to exclusively use RequireJS for node.
I cannot seem to get it all to run in the same file when i run "node r.js file.js":
define('a', function () {
console.log("loaded a");
return {};
});
require(['a'], function(a){
});
is there any way to override define and require strictly with requirejs' definitions.
Also is there a way to do this strictly with r.js and not installing requirejs npm.
You can use require.js in node!
The require.js documentation includes a section on installing require with node.js .
First, you go to the console (assuming you have npm which you should) and type:
npm install requirejs
After that, you're all set up. First you need to require require (no pun intended), so in the top of your main js file, you need something like:
var requirejs = require('requirejs');
Then, you can configure it:
requirejs.config({/*your config with shims,etc goes here*/});
That's it! You can now use it:
requirejs(["module1","module2"],function(mod1,mod2){
//whatever here
});
There are more detailed instructions on this page.
A better solution to the bigger issue:
You can use browserify.
Browserify lets you share code between the client and the server using node.js style require() statements. It shims common things for your like process.nextTick. It even shims modules like path, events and even vm.
I have personally used it in several production projects and it works.

Unable to get jasmine-jquery fixtures to load in Visual Studio with Chutzpah, or even in browser

I'm prototyping a MVC.NET 4.0 application and am defining our Javascript test configuration. I managed to get Jasmine working in VS2012 with the Chutzpah extensions, and I am able to run pure Javascript tests successfully.
However, I am unable to load test fixture (DOM) code and access it from my tests.
Here is the code I'm attempting to run:
test.js
/// various reference paths...
jasmine.getFixtures().fixturesPath = "./";
describe("jasmine tests:", function () {
it("Copies data correctly", function () {
loadFixtures('testfixture.html');
//setFixtures('<div id="wrapper"><div></div></div>');
var widget = $("#wrapper");
expect(widget).toExist();
});
});
The fixture is in the same folder as the test file. The setFixtures operation works, but when I attempt to load the HTML from a file, it doesn't. Initially, I tried to use the most recent version of jasmine-jquery from the repository, but then fell back to the over 1 year old download version 1.3.1 because it looked like there was a bug in the newer one. Here is the message I get with 1.3.1:
Test 'jasmine tests::Copies data correctly' failed
Error: Fixture could not be loaded: ./testfixture.html (status: error, message: undefined) in file:///C:/Users/db66162/SvnProjects/MvcPrototype/MvcPrototype.Tests/Scripts/jasmine/jasmine-jquery-1.3.1.js (line 103)
When I examine the source, it is doing an AJAX call, yet I'm not running in a browser. Instead, I'm using Chutzpah, which runs a headless browser (PhantomJS). When I run this in the browser with a test harness, it does work.
Is there someone out there who has a solution to this problem? I need to be able to run these tests automatically both in Visual Studio and TeamCity (which is why I am using Chutzpah). I am open to solutions that include using another test runner in place of Chutzpah. I am also going to evaluate the qUnit testing framework in this effort, so if you know that qUnit doesn't have this problem in my configuration, I will find that useful.
I fixed the issue by adding the following setting to chutzpah.json:
"TestHarnessLocationMode": "SettingsFileAdjacent",
where chutzpah.json is in my test app root
I eventually got my problem resolved. Thank you Ian for replying. I am able to use PhantomJS in TeamCity to run the tests through the test runner. I contacted the author of Chutzpah and he deployed an update to his product that solved my problem in Visual Studio. I can now run the Jasmine test using Chutzpah conventions to reference libraries and include fixtures while in VS, and use the PhantomJS runner in TeamCity to use the test runner (html).
My solution on TeamCity was to run a batch file that launches tests. So, the batch:
#echo off
REM -- Uses the PhantomJS headless browser packaged with Chutzpah to run
REM -- Jasmine tests. Does not use Chutzpah.
setlocal
set path=..\packages\Chutzpah.2.2.1\tools;%path%;
echo ##teamcity[message text='Starting Jasmine Tests']
phantomjs.exe phantom.run.js %1
echo ##teamcity[message text='Finished Jasmine Tests']
And the Javascript (phantom.run.js):
// This code lifted from https://gist.github.com/3497509.
// It takes the test harness HTML file URL as the parameter. It launches PhantomJS,
// and waits a specific amount of time before exit. Tests must complete before that
// timer ends.
(function () {
"use strict";
var system = require("system");
var url = system.args[1];
phantom.viewportSize = {width: 800, height: 600};
console.log("Opening " + url);
var page = new WebPage();
// This is required because PhantomJS sandboxes the website and it does not
// show up the console messages form that page by default
page.onConsoleMessage = function (msg) {
console.log(msg);
// Exit as soon as the last test finishes.
if (msg && msg.indexOf("Dixi.") !== -1) {
phantom.exit();
}
};
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(-1);
} else {
// Timeout - kill PhantomJS if still not done after 2 minutes.
window.setTimeout(function () {
phantom.exit();
}, 10 * 1000); // NB: use accurately, tune up referring to your needs
}
});
}());
I've got exactly the same problem. AFAIK it's to do with jasmine-jquery trying to load the fixtures via Ajax when the tests are run via the file:// URI scheme.
Apparently Chrome doesn't allow this (see https://stackoverflow.com/a/5469527/1904 and http://code.google.com/p/chromium/issues/detail?id=40787) and support amongst other browsers may vary.
Edit
You might have some joy by trying to set some PhantomJS command-line options such as --web-security=false. YMMV though: I haven't tried this myself yet, but thought I'd mention it in case it's helpful (or in case anyone else know more about this option and whether it will help).
Update
I did manage to get some joy loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment at the top of my Jasmine spec. But I still have trouble loading JSON fixtures.
Further Update
Loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment merely loads in your HTML fixtures to the Jasmine test runner, which may or may not be suitable for your needs. It doesn't load the fixtures into the jasmine-fixtures element, and consequently your fixtures don't get cleaned up after each test.

Resources