getting browserify-shim to work as expected - node.js

I am trying to get browserify-shim to work, but I can't seem to get it to create the globals I expect to see.
(note, my end goal is to get this working from gulp, but after having many problems, I figured I would eliminate one variable and try to get this working in browserify alone)
In this case, I expect "horses" to be created as a global variable pointing to the jQuery library.
// package.json
{
"version": "0.0.1",
"browser": {
"jquery": "./lib/js/vendor/jquery-2.0.2.js"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"jquery": "global:horses"
},
"devDependencies": {
// my dev dependencies
},
"dependencies": {
// my production dependencies
}
}
With this configuration, from the command line I run:
browserify common.js > mycoolfile.js
I then include mycoolfile.js into my application and run it in the browser:
<script src="mycoolfile.js"></script>
The browserified file is included fine, but when I go to chrome dev tools console and type "horses" I get an undefined error. Any thoughts on what I may be doing wrong? Thank you

I think that you want to get at jquery via exports and you are also assuming that global lets you take a global a module creates and make an alias for it, but I don't think it does that. The above might work if jquery really did have a global called horses it creates, but it won't if you just make up that name arbitrarily. I think you are trying to do something more like this:
"browserify-shim": {
"jquery": {"exports": "jQuery"}
},

Related

webpack import error with node-postgres ('pg'.Client)

Trying to bundle the following file with Webpack fails with
ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot
resolve module 'pg-native' in
.../node_modules/pg/lib/native
# ./~/pg/lib/native/index.js 9:13-33
I tried several ignore statements in the .babelrc but didnt get it running...
The test-file i want to bundle: handler.js
const Client = require('pg').Client;
console.log("done");
webpack.config.js
module.exports = {
entry: './handler.js',
target: 'node',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: __dirname,
exclude: /node_modules/,
}]
}
};
.babelrc
{
"plugins": ["transform-runtime"],
"presets": ["es2015", "stage-1"]
}
package.json
"dependencies": {
"postgraphql": "^2.4.0",
"babel-runtime": "6.11.6"
},
"devDependencies": {
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-es2015": "^6.13.2",
"babel-preset-stage-0": "^6.5.0",
"babel-polyfill": "6.13.0",
"serverless-webpack": "^1.0.0-rc.3",
"webpack": "^1.13.1"
}
Somewhat related github-issues:
https://github.com/brianc/node-postgres/issues/1187
https://github.com/serverless/serverless-runtime-babel/issues/8
This is indeed an old thread, but one that helped me nonetheless.
The solution provided by Steve Schafer 1 is good, but not the simplest.
Instead, the one provided by Marco Lüthy 2 in the linked issue is probably the easiest to set up because it is pure configuration, without even the need for a dummy file to be created.
It consists of modifying your Webpack config plugins array as follows:
const webpack = require('webpack');
const webpackConfig = {
...
resolve: { ... },
plugins: [
new webpack.IgnorePlugin(/^pg-native$/)
// Or, for WebPack 4+:
new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ })
],
output: { ... },
...
}
Updated to include a change suggested in the comments.
This is an old thread but the problem still exists, so for anyone experiencing it, there is a workaround. The problem is an interaction between the way that node-postgres is written and how babel rewrites the code, which forces pg-native to be loaded even when you don't explicitly import/require it.
The simplest workaround is to add a couple of aliases to your webpack.config.js to cause it to link in a dummy do-nothing file instead:
{
...
resolve: {
alias: {
...
'pg-native': path-to-dummy-js-file,
'dns': path-to-dummy-js-file
}
}
...
}
where the dummy file contains a single line:
export default null
See https://github.com/brianc/node-postgres/issues/838 for further discussion and alternative workarounds.
I know that this is an old topic but I'm compelled to share how I solved it. It was maddening to deal with.
So, here is the readers digest version as based on the recollection from the last brain cell that I have.
Error:
Webpack Compilation Error ./node_modules/pg/lib/native/client.js Module not found: Error: Can't resolve 'pg-native'
The error above was thrown when attempting to run a Cypress test that required the npm package 'pg'.
Attempting to install the pg-native package was not successful and resulted in another error; namely ->
Call to 'pg_config --libdir' returned exit status 1 while in binding.gyp. while trying to load binding.gyp
I found that executing pg_config --libdir in the VSCode cmd prompt resulted in that command failing.
However, I knew that it should work since running that command from the system command prompt resulted in this -> C:/PROGRA~1/POSTGR~1/9.3/lib
That is the path that contains a required dll.
So, instead of running npm install from the VSCode command prompt, I ran it from the command prompt as launched from windows.
The result...success!!! pg-native was installed successfully.
After, the Cypress test was able to run as well.
Errors in now way helped me to arrive at this solution. It was more just checking that things were installed that were required, etc.
You may have pg-native globally installed locally. Hence the packet manager does not include the pg-native in the lock file. That was a issue i experienced where it did run fine locally but every time i build in the cloud webpack complained about pg-native missing. I solved it by removing the lockfile in the files pushed to the cloud (In this case seed.run).

shimming linkurious - how to configure?

I'm trying to use the linkurious library (a sigma fork), which provides a "main": "dist/sigma.require.js" (in the package.json). this allows me to do:
var sigma = require('linkurious');
however, the plugins are not included so I have to require them separately. the problem is that the plugins rely on the sigma variable being available in the global scope. so I've shimmed things as follows (from the package.json):
"browser": {
"sigma": "./node_modules/linkurious/dist/sigma.js",
"linkurious/plugins": "./node_modules/linkurious/dist/plugins.js"
},
"browserify-shim": {
"sigma": {"exports": "sigma"},
"linkurious/plugins": { "depends": [ "sigma" ] }
},
"browserify": {
"transform": [ "browserify-shim" ]
},
which, when run in a browser doesn't generate errors during inclusion of the plugins (I gather this means the global variable is available) but references to the plugins fail (as if they failed to attach themselves, or attached themselves to a non-global variable).
I'm using grunt-browserify to run the process where I have it configured like this (from the Gruntfile.js):
grunt.initConfig({
browserify: {
libs: {
files: { 'inc.js': ['index.js'] },
},
}
});
I've attached a little project to this issue with the minimal required code to demonstrate the problem in the hopes that someone else can replicate/figure out. unpack, type npm install; npm start and run a browser against http://localhost:8002/ to see the issue.
thanks in advance,
ekkis
sigma.zip
- edit I -
incidentally, bendrucker at the git repo (see: https://github.com/thlorenz/browserify-shim/issues/215) suggests I need to do a global transform. It's been explained to me that shimming doesn't work on node_modules files and for those I need a global transform. this doesn't make much sense to me as the whole point of shimming is that you don't own the code you're shimming. in any case, bendrucker pointed me to this other SO post where the question is posed but no answers are provided.
help?

Proper use of karma-commonjs with Jasmine 2

I've spent a fair amount of time trying to debug this, and figured I would ask. I even created a GitHub repository but won't rely on it, so here goes. I'm trying to take advantage of CommonJS syntax within the Karma test runner using PhantomJS. For my module I created the simplest thing I could think of:
exports.returnYes = function() {
return "Yes";
};
The Jasmine test is:
var returnYes = require("../js/returnYes").returnYes;
describe("returnYes", function() {
it("should return Yes", function() {
expect(returnYes()).toBe("Yes");
});
});
And, if I do a jasmine init I can run it from the command line thanks to jasmine-npm by simply typing jasmine with output:
$ jasmine
Started
.
1 spec, 0 failures
Finished in 0.003 seconds
Now to try and get it to work inside karma:
I create my karma.conf.js with frameworks: jasmine,commonjs. And, I add commonjs as preprocessor.
I try to do a karma run and I find that it can't find global which is part of getJasmineRequireObj in jasmine.js where it declares jasmineGlobal = global;
The command line output is a little hard to read, but here it is:
$ karma run
[2015-06-27 17:41:35.266] [DEBUG] config - Loading config /Users/zen/Projects/karma-commonjs-test/karma.conf.js
##teamcity[enteredTheMatrix]
##teamcity[testSuiteStarted nodeId='1' parentNodeId='0' name='karma.conf.js' nodeType='config' locationHint='config:///Users/zen/Projects/karma-commonjs-test/karma.conf.js']
##teamcity[testSuiteStarted nodeId='2' parentNodeId='1' name='PhantomJS 1.9.8 (Mac OS X 0.0.0)' nodeType='browser']
##teamcity[testStarted nodeId='3' parentNodeId='2' name='Error' nodeType='browserError']
##teamcity[testFailed nodeId='3' error='yes' message='ReferenceError: Can|'t find variable: global|nat http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?68f13ab3f93af5a219b9fe8409f8763b31998bba:27']
##teamcity[testSuiteFinished nodeId='2']
##teamcity[testSuiteFinished nodeId='1']
For good measure here are the devDependencies in my packages.json:
"devDependencies": {
"jasmine-core": "^2.3.4",
"karma": "^0.12.37",
"karma-commonjs": "0.0.13",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^0.2.0",
"phantomjs": "^1.9.17"
}
I'm not sure why I can't find global. Any help would be greatly appreciated!!! :)
It seems like my whole problem came down to the line in karma.conf.js (not shown in my original question:
preprocessors: {
'**/*.js': ['commonjs']
},
For some reason, jasmine.js is not happy being pre-processed by commonjs, and "**/*.js" says to go through all subdirectories (which is probably overkill), including node_modules which has jasmine-core/jasmine.js
So I can either make my pre-processor more specific (best practice):
preprocessors: {
'spec/*.js': ['commonjs'],
'js/*.js': ['commonjs']
},
but as a test to see if any other files would give me a problem, I tried:
preprocessors: {
'**/!(jasmine).js': ['commonjs'],
},
And, everything worked as well. Bottom line. Do not process jasmine.js through commonjs preprocessor!

ESLint - "window" is not defined. How to allow global variables in package.json

I am assigning a property to the global window object, but when I run eslint, I get this:
"window" is not defined
I see this here in the eslint docs:
the following defines window as a global variable for code that should not trigger the rule being tested:
valid: [
{
code: "window.alert()",
globals: [ "window" ]
}
]
I've tried adding something like this to the package.json file to have eslint allow "window" as a global variable, but I must be doing something wrong. From the docs it seems like I might need to do something like this in a separate file, but is there a way to define some allowed global variables right in the package.json file?
There is a builtin environment: browser that includes window.
Example .eslintrc.json:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: https://eslint.org/docs/user-guide/configuring/language-options#specifying-environments
Also see the package.json answer by chevin99 below.
I found it on this page: http://eslint.org/docs/user-guide/configuring
In package.json, this works:
"eslintConfig": {
"globals": {
"window": true
}
}
Add .eslintrc in the project root.
{
"globals": {
"document": true,
"foo": true,
"window": true
}
}
Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.
{
"env": {
"browser": true,
"node": true
}
}
I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:
Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):
/* eslint-env browser */
This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.
There are plenty of environments, and you can declare more than one at the same time, for example, in-line:
/* eslint-env browser, node */
If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.
From their docs:
An environment defines global variables that are predefined. The
available environments are:
browser - browser global variables.
node - Node.js global variables and Node.js scoping.
commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
shared-node-browser - Globals common to both Node and Browser.
[...]
Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:
/* eslint-disable no-console */
You can see the list of all rules, including recommended rules to have for best coding practices.
If you are using Angular you can get it off with:
"env": {
"browser": true,
"node": true
},
"rules" : {
"angular/window-service": 0
}

Problems with behat + mink

I'm trying to install behat + mink (on kohana framework, not symfony, I'm putting behat into the modules folder - I'm writting this just in case, but I guess that's not what causes my problem).
I am having the same search.feature file as it is in behat documentation, I'm changing features/bootstrap class into the:
<?php
use Behat\Behat\Context\ClosuredContextInterface,
Behat\Behat\Context\TranslatedContextInterface,
Behat\Behat\Context\BehatContext,
Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;
/**
* Features context.
*/
class FeatureContext extends MinkContext
{
}
And when I type "behat" in the CLI I get the following error: Call to a member function getSession() on a non object in .....RawMinkContext.php on line 80.
I've read somewhere that it's the behat.yml file which causes this error. I think the right thing to do is to create new behat.yml file in the root of the installed behat folder and put this code inside:
default:
extensions:
Behat\MinkExtension\Extension:
base_url: http://wikipedia.org
goutte: ~
selenium2: ~
paths:
features: features
bootstrap: features/bootstrap
annotations:
paths:
features: features/annotations
closures:
paths:
features: features/closures
But of couse it gives me the same error. I've tried a lot of configurations: copying only extensions part, changing default into context, copying the same content into three other behat.yml files (vendor/behat/behat, and vendor/behat/monk, and vendor/behat/monk-ententions) - none works.
Can someone tell me what's the right way to set this? Maybe someone here also had problems with that...
BTW. When I installed behat withough goutte, only with selenium2 driver, I was getting errors that goutte is not installed. But when I installed it with goutte, I was getting errors that there's no fabpot/goutte directory (or fapbot/, I don't remember, but I guess it was the first one :D), so I deleted everything and reinstalled behat with the following composer.json file, maybe this also has something to do with this error:
{
"name": "behat/mink-browserkit-driver",
"description": "Symfony2 BrowserKit driver for Mink framework",
"keywords": ["Symfony2", "testing", "browser"],
"homepage": "http://mink.behat.org/",
"type": "mink-driver",
"license": "MIT",
"authors": [
{
"name": "Konstantin Kudryashov",
"email": "ever.zet#gmail.com",
"homepage": "http://everzet.com"
}
],
"require": {
"php": ">=5.3.1",
"symfony/browser-kit": ">=2.0.0,<2.2.0",
"symfony/dom-crawler": ">=2.0.0,<2.2.0",
"behat/behat": "2.4.*#stable",
"behat/mink": "1.4.*#stable",
"behat/mink-extension": "*",
"behat/mink-goutte-driver": "*",
"behat/mink-selenium2-driver": "*"
},
"minimum-stability": "dev",
"autoload": {
"psr-0": {
"Behat\\Mink\\Driver": "src/"
}
},
"config": {
"bin-dir": "bin/"
}
}
The recommended way to install Behat+Mink for anything, not just Kohana, is via Composer. See http://docs.behat.org/quick_intro.html for instructions. The autoload clause you have in your composer.json is not required.
As for your modules attempt, KO3.2 does not yet have the ability to load PSR-0 and so putting it in modules will not allow it to be loaded correctly.
Don't randomly copy your behat.yml - you only need one copy in your project root. If you are worried, you can explicitly load your behat.yml via bin/behat -c /path/to/behat.yml
With your composer.json set up correctly to have mink dependencies, you can then just do bin/behat -dl to verify mink works.
You can then do bin/behat --init to create your features filestructure.
This will create a FeatureContext which overrides Mink's definitions, so add
require_once __DIR__.'/../../vendor/autoload.php';
and change the class definition to:
class FeatureContext extends Behat\MinkExtension\Context\MinkContext
in your features/bootstrap/FeatureContext.php file.
Everything should work as expected now. I recently did a Behat+Mink+KO3 setup, feel free to see how I did it here: https://github.com/Moult/Eadrax/commit/b5dd813c92b82aea29eea13b5a30bae170aa57e6

Resources