cypress-browserify-preprocessor
cypress-browserify-preprocessor copied to clipboard
Need example transpiling es6 modules in node_modules folder
If the client wants to use import { merge } from 'lodash-es'; then we need to show how to modify browserify options to transpile node_modules folder
Cypress 3.1.0
For https://github.com/cypress-io/cypress/issues/2679
Solution
- install https://github.com/cypress-io/cypress-browserify-preprocessor
- add to
cypress/plugins/index.js
const browserify = require('@cypress/browserify-preprocessor')
module.exports = (on) => {
const options = browserify.defaultOptions
// print options to find babelify, it is inside transforms at index 1
// and it is [filename, options]
const babelOptions = options.browserifyOptions.transform[1][1]
babelOptions.global = true
// ignore all modules except files in lodash-es
babelOptions.ignore = [/\/node_modules\/(?!lodash-es\/)/]
// if you want to see the final options
// console.log('%o', babelOptions)
on('file:preprocessor', browserify(options))
}
Example cypress/integration/spec.js file
// use es6 module from node_modules
import { merge } from 'lodash-es';
// use our es6 module (works right out of the box)
import { foo } from './foo';
describe('Preprocessor Reproducer', () => {
it('test', () => {
expect(foo).to.equal('foo')
expect(merge({ foo: 'bar'}, { baz: 'bar'})).to.deep.equal({
foo: 'bar',
baz: 'bar'
})
})
});
there is noticeable transpile time for the test (this is why people recommend NOT to transpile es6), but the test passes

note: https://github.com/babel/babelify#why-arent-files-in-node_modules-being-transformed
For people seeking the same with typescript: until #61 is fixed, you can go with this workaround:
Object.defineProperty(options.browserifyOptions.transform, 'filter', {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: function<TType extends string>(this: TType[], filterCallback: (value: TType, index: number, array: TType[]) => boolean, thisArg?: any) {
const output = [];
const callback = thisArg ? filterCallback.bind(thisArg) : filterCallback;
for (let index = 0; index < this.length; index++) {
if (Array.isArray(this[index]) && typeof this[index][0] === 'string' && this[index][0].includes('babelify')) {
output.push(this[index]);
continue;
}
if (Array.isArray(this[index]) && typeof this[index][0] === 'string' && this[index][0].includes('coffeeify')) {
continue;
}
if (callback(this[index], index, this)) {
output.push(this[index]);
}
}
return output;
},
enumerable: false,
});