Using the FileAPI library with browserify - browserify

The FileAPI library (https://github.com/mailru/FileAPI/issues/202) does not officially support CommonJS modules. I've tried using browserify-shim but I'm not able to make it work. After requireing fileapi I just get an empty object back. I've created a repo for reproduction here https://github.com/Prinzhorn/browserify-fileapi
Relevant package.json part
{
"dependencies": {
"fileapi": "2.0.15"
},
"devDependencies": {
"browserify": "11.1.0",
"browserify-shim": "3.8.10"
},
"browser": {
"fileapi": "./node_modules/fileapi/dist/FileAPI.html5.js"
},
"browserify-shim": {
"fileapi": "FileAPI"
}
}
If you want to try it locally:
git clone git#github.com:Prinzhorn/browserify-fileapi.git
npm install
npm run build
chromium-browser index.html
Check out the console in Chromium, you'll see an empty array from running console.log(Object.keys(require('fileapi'))). Note that there is a global window.FileAPI with the correct API.
Does anyone know if browserify-shim is able to shim FileAPI? Because I believe it does some exotic things to manage it's dependencies (the concatenated files expect certain globals).

You'll need to tell browserify to use browserify-shim as a transform in the package.json as outlined in this example
Mainly you're missing:
"browserify": {
"transform": [ "browserify-shim" ]
}

Related

Running Mocha 6 ES6 tests with Babel 7, how to set up?

For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.
My dev dependencies look like this (package.json):
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"sinon": "^7.3.2"
},
My build and test scripts looks like this (package.json):
"scripts": {
"test": "mocha --require #babel/register",
"build": "babel src -d dist --presets=#babel/preset-env"
},
Running npm run build works well. The dist/ folder gets populated with transpiled files.
Running npm run test does not seem to work - this is my problem.
> mocha --require #babel/register
/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: regeneratorRuntime is not defined
Initially I got an import error, which was resolved by adding .babelrc file.
Below is my .babelrc file content.
{
"presets": ["#babel/preset-env"]
}
I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.
What is needed to set this up properly?
I am not using webpack.
Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
Look at the project documentation:
npm install --save-dev babel-register
In your package.json file make the following changes:
{
"scripts": {
"test": "mocha --require babel-register"
}
}
Some features will require a polyfill:
npm install --save-dev babel-polyfill
{
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
}
Below steps are for applying Babel transformations & core-js polyfills for your tests file:
💡 All transformations are only done per current environment, so only what is needed to be transpiled/polyfilled, will be. Target environments may be defined from a .browserslist file or as a property in package.json file. (read more here)
Step 1: Install packages:
#babel/core (read why)
#babel/preset-env (read why)
#babel/register (read why)
core-js (read why)
Note that #babel/polyfill exists and uses core-js under the hood. However, it was deprecated in favor of using core-js directly.
Step 2: Create a Babel configuration file babel.config.js
(used to be .babelrc.js or a .json file).
Create this file at the root-level of your code.
The most basic configuration (for just testing and not bundling) would look like this:
module.exports = {
presets: [
['#babel/preset-env', {
"corejs": "3.26",
"useBuiltIns": "usage"
}],
};
corejs - This is the polyfills library and should be specified with the minor version, otherwise x.0 will be used.
It is needed when testing code on rather "old" Node versions, which do not support all of the language methods. This ofc depends on your own usage of such javascript methods. (for example String.prototype.replaceAll).
useBuiltIns - must be set in order for the corejs polyfills to be applied. Read about it in the official docs.
By default, #babel/preset-env will compile your code for the current environment, but you can specify a different environment by setting the "targets" option in the configuration.
Ofc, you can add more presets like #babel/preset-react for example, if your code it written in React, or any other plugins which are specifically needed for your code.
Step 3: Connect mocha to the babel configuration:
In your package.json file
Under the scripts section, simply write something like this:
"test": "mocha \"src/**/*.test.js\""
Create a .mocharc.json file with this content:
{
"exit": true,
"color": true,
"require": ["#babel/register"],
"ignore": "node_modules"
}
This will apply Babel transformations to all of your test files.
If you need need to apply some special global javascript before/to all of your tests, you can add another file to the require setting, for example, fixtures.cjs:
"require": ["#babel/register", "fixtures.cjs"],
fixtures.cjs:
Below example applies a chai (popular alongside Mocha) plugin for testing DOM-related code:
var chai = require('chai'),
chaiDOM = require('chai-dom');
// https://stackoverflow.com/questions/62255953/chai-usechaihttp-once-or-in-every-test-file
// https://mochajs.org/#global-teardown-fixtures
exports.mochaGlobalSetup = function () {
chai.use(chaiDOM);
}
Interesting reads:
Babel vs babel-core vs babel-runtime
How does mocha / babel transpile my test code on the fly?

Use stream-browserify with expo

stream cannot be used with expo, as it is a Node.js standard package. However, the package stream-browserify can be used as an alternative in those scenarios.
In order to make modules resolve this instead of the native Node package, I am trying to make babel-plugin-require-rewrite work with expo.
I am adding this to babel.config.js:
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
["rewrite-require", { aliases: {
"stream": "stream-browserify"
}}]
]
};
};
Unfortunately, it is not respected by the bundler. I get this error when trying:
The package at "node_modules\qr-image\lib\qr.js" attempted to import the Node standard library module "stream". It failed because React Native does not include the Node standard library. Read more at https://docs.expo.io/versions/latest/introduction/faq.html#can-i-use-nodejs-packages-with-expo
Is it possible to make this work in Expo?
You dont need to modify babel config to use stream-browserify in your source. You can import stream-browserify in your App.js. I have created a simple example on GitHub.
App.js
const Stream = require('stream-browserify');
Package.json
"dependencies": {
"buffer": "^5.2.1",
"events": "^3.0.0",
"stream-browserify": "^2.0.2",
"readable-stream": {
"version": "2.3.6",
"dependencies": {
"core-util-is": "github:mjmasn/core-util-is"
}
}
...
}
stream-browserify has dependency readable-stream which has its own dependency and use node environment. To resolve it you have to add these node packages. You can read about core-util-is fork here.
This answer rn-nodeify install that i have posted should work. Except Step 1 & Step 5 follow all steps. Step 3 is used for adding node packages you are specifically looking to install, in this case specify stream. Please do modifications in Step 4 based on your requirement in Step 3.
Please do comment if you want me to elaborate.
What ended up working for me was creating a metro.config.js file with the following content (I used readable-stream instead of stream-browserify, but I think either should work):
module.exports = {
resolver: {
extraNodeModules: {
stream: require.resolve('readable-stream'),
},
},
};
And then I just used yarn add readable-stream and this allows dependencies to use readable-stream as if it were stream.
This was based on the info I found here: https://gist.github.com/parshap/e3063d9bf6058041b34b26b7166fd6bd#file-node-modules-in-react-native-md

NPM - How do I override one of my dependencies dependency? [duplicate]

I would like to use the grunt-contrib-jasmine NPM package. It has various dependencies. Part of the dependency graph looks like this:
─┬ grunt-contrib-jasmine#0.4.1
│ ├─┬ grunt-lib-phantomjs#0.2.0
│ │ ├─┬ phantomjs#1.8.2-2
Unfortunately, there's a bug in this version phantomjs which prevents it from installing correctly on Mac OS X. This is fixed in the latest version.
How can I get grunt-lib-phantomjs to use a newer version of phantomjs?
Some additional context:
grunt-contrib-jasmine explicitly requires version "~0.2.0" of grunt-lib-phantomjs, which explicitly requires version "~1.8.1" of phantomjs.
Adding phantomjs to my package's dependencies first has no effect; both versions are installed and grunt-contrib-jasmine still uses the older versions (see: When installing a package with NPM, can you tell it to use a different version of one of its dependencies?).
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "grunt-contrib-connect#0.3.0",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect#~2.7.3"
}
}
}
}
}
npm should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
As of npm cli v8.3.0 (2021-12-09) this can be solved using the overrides field of package.json. As described in StriplingWarrior's answer
For example, the project has typescript version 4.6.2 as direct development dependency and awesome-typescript-loader that uses old version 2.7 of typescript. Here is how you can tell npm to use version 4.6.2 of typescript for awesome-typescript-loader:
{
"name": "myproject",
"version": "0.0.0",
"scripts": ...
"dependencies": ...
"devDependencies": {
"typescript": "~4.6.2",
"awesome-typescript-loader": "^5.2.1",
...
},
"overrides": {
"awesome-typescript-loader": {
"typescript": "$typescript"
}
}
}
If you don't use typescript as direct development dependency, then you have to write 4.6.2 instead of $typescript in overrides section:
{
"name": "myproject",
"version": "0.0.0",
"scripts": ...
"dependencies": ...
"devDependencies": {
"awesome-typescript-loader": "^5.2.1",
...
},
"overrides": {
"awesome-typescript-loader": {
"typescript": "~4.6.2"
}
}
}
For using the latest version of dependency:
{
"name": "myproject",
"version": "0.0.0",
"scripts": ...
"dependencies": ...
"devDependencies": {
"awesome-typescript-loader": "^5.2.1",
...
},
"overrides": {
"awesome-typescript-loader": {
"typescript": "latest"
}
}
}
Same overrides can be used for both dependencies and devDependencies.
If you're using npm version >5 but <8.3.0: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".
For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"glob": "7.1.2",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
}
},
Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
},
"dependencies": {
"glob": {
"version": "3.2.11"
}
}
},
Now remove your node_modules folder, run npm ci (or npm install for old version of node/npm) and it will add missing parts to the "dependencies" section.
As of NPM v8.3, the correct way to deal with this is via the overrides section of your package.json file.
If you need to make specific changes to dependencies of your
dependencies, for example replacing the version of a dependency with a
known security issue, replacing an existing dependency with a fork, or
making sure that the same version of a package is used everywhere,
then you may add an override.
Overrides provide a way to replace a package in your dependency tree
with another version, or another package entirely. These changes can
be scoped as specific or as vague as desired.
To make sure the package foo is always installed as version 1.0.0 no
matter what version your dependencies rely on:
{
"overrides": {
"foo": "1.0.0"
}
}
There are a variety of other, more nuanced configurations allowing you to only override a package when it's a dependency of a particular package hierarchy. For more details, check out https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides
The only solution that worked for me (node 12.x, npm 6.x) was using npm-force-resolutions developed by #Rogerio Chaves.
First, install it by:
npm install npm-force-resolutions --save-dev
You can add --ignore-scripts if some broken transitive dependency scripts are blocking you from installing anything.
Then in package.json define what dependency should be overridden (you must set exact version number):
"resolutions": {
"your-dependency-name": "1.23.4"
}
and in "scripts" section add new preinstall entry:
"preinstall": "npm-force-resolutions",
Now, npm install will apply changes and force your-dependency-name to be at version 1.23.4 for all dependencies.
For those using yarn.
I tried using npm shrinkwrap until I discovered the yarn cli ignored my npm-shrinkwrap.json file.
Yarn has https://yarnpkg.com/lang/en/docs/selective-version-resolutions/ for this. Neat.
Check out this answer too: https://stackoverflow.com/a/41082766/3051080
Nested replacement with an entirely different package
Most of the strategies outlined in the other answers here work well if you are just interested in overriding the package's version number, but in our case, we needed to find a way to override a nested npm sub-dependency with a different package altogether. For details on why you would ever want to do this, please refer to the following question:
How to override a nested npm sub-dependency with a different package altogether (not just different package version number)?
Specify the tarball directly
For nested replacement of a package with an entirely different package using the npm-force-resolutions strategy that others have mentioned, you just need to provide a link to the tarball where you would normally specify the overriding version number.
As an example, for the case of replacing the vulnerable package, ansi-html, with the fixed fork of this package, ansi-html-community, your resolutions section of package.json should look like this:
"resolutions": {
"ansi-html": "https://registry.npmjs.org/ansi-html-community/-/ansi-html-community-0.0.8.tgz"
}
To find the link to the tarball, use the following command, modifying your registry as necessary:
npm view ansi-html-community dist.tarball --registry=https://registry.npmjs.org/
Also, note that for npm-force-resolutions to work when you run npm install, you will need a preinstall entry under the scripts section of package.json:
"scripts": {
"preinstall": "npx npm-force-resolutions"
}
#user11153 's answer worked for me locally, but when trying to do a clean install (aka deleting node_modules), I would get:
npm-force-resolutions: command not found
I had to update the preinstall script to be:
"preinstall": "npm i npm-force-resolutions && npm-force-resolutions"
Which ensures that npm-force-resolutions package is installed before attempting to run it.
That being said, if you're able to use yarn instead, I would do that and then use #Gus 's answer.
I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:
Remove the nested dependency under the 'requires' section in package-lock.json
Add the updated dependency under DevDependencies in package.json, so that modules that require it will still be able to access it.
npm i
I was about to go down the npm-force-resolutions route but it seems that simply including the dependency in my own package.json fixed the problem for me.
I believe this worked in my case because the original dependency allows for patch versions of the dependency in question that I wanted to update. Thus by manually including a newer version it still fulfilled the dependency of the original dependency and will use the one I've manually added.
Example
Problem
I need to update plyr to version 3.6.9 from 3.6.8
Mine
package.json
{
"dependencies": {
"react-plyr": "^3.2.0"
}
}
React Plyr
package.json
{
"dependencies": {
"plyr": "^3.6.8"
}
}
Notice for the plyr dependency it starts with ^ this means it can accept any minor patches. You can learn more about that here:
https://docs.npmjs.com/about-semantic-versioning#using-semantic-versioning-to-specify-update-types-your-package-can-accept
Updating Mine
This updates the plyr dependency from my package.json.
package.json
{
"dependencies": {
"plyr": "^3.6.9",
"react-plyr": "^3.2.0"
}
}
Based on the rest of the answers, I provide the same solution, but I display the package.json, as I struggled a little bit on where to place the override and how.
{
"name": "my-app",
"version": "snapshot",
"scripts": {
"ng": "ng",
"build-dev": "ng build --configuration development",
},
"private": true,
"dependencies": {
"#angular/animations": "~14.2.9",
"#angular/common": "~14.2.9"
...
},
"devDependencies": {
"#angular-devkit/build-angular": "^14.2.8",
....
},
"overrides": {
"loader-utils#>2.0.0 <3": "2.0.4",
"loader-utils#>3.0.0 <4": "3.2.1"
}
}
For November 2022 "loader-utils" security vulnerability, it was requested to
use the version 2.0.4, if you are in the 2.X
use the version 3.2.1, if you are in the 3.X
And to verify
add the package.json the override tag
delete the package-lock.json
run "npm install"
run "npm audit"
Run this first
npm i -D #types/eslint#8.4.3
it will solve the issue

Gulp + Browserify + Jquery + Bootstrap

I'm trying to load jquery + jquery-ui + bootstrap inside my project throught NPM and gulp.
My configuration is this:
Package.json
"browser": {
"jquery": "/node_modules/jquery/dist/jquery.js",
"jquery-ui": "/node_modules/jquery-ui-browserify/jquery-ui.js"
},
"browserify-shim": {
"jquery": "$",
"jquery-ui": {
"exports": "jquery-ui",
"depends": [ "jquery:jQuery" ]
}
},
"browserify": {
"transform": [ "browserify-shim" ]
},
"dependencies": {
"bootstrap": "^3.3.6",
"jquery": "2.1.0",
"jquery-ui-browserify": "^1.11.0-pre-seelio",
}
gulpfile.js
gulp.task('browserify', function(){
return browserify([
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-ui-browserify/dist/jquery-ui.js',
'node_modules/bootstrap/dist/js/bootstrap.js',
])
.bundle()
.pipe(source('core.js'))
.pipe(buffer())
.pipe(gulp.dest('build/js'));
});
Then I load core.js with assetic from my index.php but I get this error:
Uncaught ReferenceError: jQuery is not defined
What am I doing wrong?
Thank you.
I don't know what you're trying to do there but keep in mind that what you should pass to the browserify instance is the entry point of your application, not your dependencies.
Then in your application you can use the require function to load those dependencies:
var $ = require('jquery');
While compiling browserify will autonomously do two things for you:
He will put into your bundle any library you required.
He will resolve your require statements by replacing them with a reference to the bundled copy of that library.
As long as the library is installed through npm you don't need any additional configuration. On the other hand if the library is situated in an unconventional location you'll need to tell browserify how to resolve it.
Anyway you can find more documentation on the repo's readme

Where is jquery getting required from? - browserify - browserify-shim

I am building a project with broweserify, jquery and jquery-ui. All libs were pulled down with npm. Here is how I am using my browserify-shim to pull in jquery' and 'jquery-ui:
"browserify": {
"transform": [ "browserify-shim" ]
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
"jquery-ui": "./node_modules/jquery-ui/jquery-ui.js"
},
"browserify-shim": {
"jquery": "$"
}
Everything works like it should, but I look at jquery-ui.js and the first line of code is
var jQuery = require('jquery');
How is this line of code being resolved? When I put a debuggerstatement after this, jquery is always resolved. I even changed the name of jquery in my shim and the it still resolved. How is that happening?
Short answer: your package.json dependencies
Long answer: I'm also using those npm modules. That jquery-ui package seems to have been retooled to require its internal dependencies. As you note, the first line of the jquery-ui core.js is: var jQuery = require('jquery'); which looks for a module called jquery in the project's npm dependencies. That's handled by something like what I have in my package.json:
"dependencies": {
"jquery": "^2.1.1",
"jquery-ui": "^1.10.5",
}
in addition to the browserify parts:
"browserify": {
"transform": [ "browserify-shim" ]
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.min.js",
"jq-ui": "./node_modules/jquery-ui/jquery-ui.js"
},
"browserify-shim": {
"jquery": "$",
"jq-ui": {
"exports": "jq-ui",
"depends": [ "jquery:jQuery" ]
},
}
What I haven't figured out is whether we can use the jQuery UI components in our other client-side scripts.
See also:
* Using Browserify with jquery and non-npm plugins
* Using Browserify with jQuery plugins
If you installed jquery and jquery-ui with npm, then I suspect they're somewhere in the rest of your dependencies. In that case, you're actually not using the "browser" "jquery" property, but instead letting browserify use it's non-shimmed "require" process.
Is "jquery" in your "dependencies" list? What happens if you delete that "browser" "jquery" line entirely?