Cypress Webpack Compilation Error create-react-app - javascript

const findWebpack = require('find-webpack');
const injectDevServer = require('#cypress/react/plugins/react-scripts');
const webpackPreprocessor = require('#cypress/webpack-preprocessor');
/**
* #type {Cypress.PluginConfig}
*/
module.exports = (on, config) => {
// const webpack = require('./webpack.config.js');
// find the Webpack config used by react-scripts
const webpackOptions = findWebpack.getWebpackOptions();
if (!webpackOptions) {
throw new Error('Could not find Webpack in this project 😢');
}
// if we just pass webpackOptions to the preprocessor
// it won't work - because react-scripts by default
// includes plugins that split specs into chunks, etc.
// https://github.com/cypress-io/cypress-webpack-preprocessor/issues/31
// solution 1
// blunt: delete entire optimization object
// delete webpackOptions.optimization
// solution 2
// use a module that carefully removes only plugins
// that we found to be breaking the bundling
// https://github.com/bahmutov/find-webpack
const cleanOptions = {
reactScripts: true,
};
findWebpack.cleanForCypress(cleanOptions, webpackOptions);
const options = {
webpackOptions,
watchOptions: {},
};
injectDevServer(on, config);
on('file:preprocessor', webpackPreprocessor(options));
return config;
};
Hi, after migration from cypress 9.5.4 to 10.11.0 I have a lot of Webpack Compilation Errors that i didnt have before. Some of them I solved with "#cypress/webpack-preprocessor": but some of them I couldnt resolve. Can you help me with the problem on screen?Webpack compilation error screen

Related

Not able to remove duplicate (dependent) entries while doing code split using webpack

I am using webpack 5.12.3 for bundle split.
He is my webpack.config.js
const { resolve } = require('path')
const webpack = require('webpack')
const TerserPlugin = require('terser-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const { getIfUtils, removeEmpty } = require('webpack-config-utils')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = env => {
const { ifProduction, ifNotProduction } = getIfUtils(env)
const mode = ifProduction('production', 'development')
return {
mode,
//context: resolve('./src/public/js'),
entry: {
index: './.dist/public/main.js',
},
output: {
filename: '[name].min.js',
chunkFilename: '[name].min.js',
path: resolve('./src/public/js/'),
pathinfo: true,
},
}
remaining code contains rules,optimzations,minimizers etc.
Here is main.js which is used in webpack config entry
import 'babel-polyfill';
var Routes = require('../routes/react.jsx');
var Client = require('react-engine/lib/client');
// Include all view files. Browerify doesn't do
// this automatically as it can only operate on
// static require statements.
// Not required as part for webpack.
//require('./views/**/*.jsx', {glob: true});
// boot options
var options = {
routes: Routes,
// supply a function that can be called
// to resolve the file that was rendered.
viewResolver: function viewResolver(viewName) {
return require('./views/' + viewName);
}
};
document.addEventListener('DOMContentLoaded', function onLoad() {
console.log(typeof(options));
console.log(options);
Client.boot(options);
});
Here for all pages in application this code is getting executed only one bundle file is created. My aim is to have separate bundle for every page in /src/views . I did try to get viewName from viewResolver its not getting executed . Can anyone please suggest me how should I change code so that I can have entry for every page (that is possible using entry section of webpack config) but as everything is coming to main.js . If I try to add another main1.js what should be its code and how execution should come there ?

How to setup clipboardy in cypress 10?

I'm pretty new to cypress. I tried to install clipboardy to one of my project.
But the guide that I found online like this mostly setup on the older cypress which is using the plugins/index.js file.
I tried something like this and got error
const { defineConfig } = require("cypress");
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin =
require("#badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const clipboardy = require("clipboardy");
module.exports = defineConfig({
e2e: {
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
on("file:preprocessor", bundler);
await addCucumberPreprocessorPlugin(on, config);
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
return config;
},
specPattern: "cypress/e2e/features/*.feature",
baseUrl: "XXXXXXXXXXXXX",
chromeWebSecurity: false,
},
});
The error
Error screen
Stack Trace
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\node_modules\clipboardy\index.js from C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js not supported.
Instead change the require of index.js in C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js to a dynamic import() which is available in all CommonJS modules.
at Object. (C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js:8:20)
at async Promise.all (index 0)
at async loadFile (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:106:14)
at async EventEmitter. (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:116:32)
It's because the clipboardy package has type: "module" in it's 'package.json'.
This tells anything that uses the package that you should use import not require to load the package.
Use dynamic imports, as hinted in the error message
Instead change the require of index.js in ... to a dynamic import()
const clipboard = import('clipboardy')

Gulp browserify task stuck

Gulp terminal seems to get stucked after browserify-ing my main.js. Below is my gulpfile.babel.js
'use strict';
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSyncLib from 'browser-sync';
import pjson from './package.json';
import minimist from 'minimist';
import glob from 'glob';
// Load all gulp plugins based on their names
// EX: gulp-copy -> copy
const plugins = gulpLoadPlugins();
const defaultNotification = function(err) {
return {
subtitle: err.plugin,
message: err.message,
sound: 'Funk',
onLast: true,
};
};
let config = Object.assign({}, pjson.config, defaultNotification);
let args = minimist(process.argv.slice(2));
let dirs = config.directories;
let taskTarget = args.production ? dirs.destination : dirs.temporary;
// Create a new browserSync instance
let browserSync = browserSyncLib.create();
// This will grab all js in the `gulp` directory
// in order to load all gulp tasks
glob.sync('./gulp/**/*.js').filter(function(file) {
return (/\.(js)$/i).test(file);
}).map(function(file) {
require(file)(gulp, plugins, args, config, taskTarget, browserSync);
});
// Default task
gulp.task('default', ['clean'], () => {
gulp.start('build');
});
// Build production-ready code
gulp.task('build', [
'browserify'
]);
// Testing
gulp.task('test', ['eslint']);
This is my browserify.js
'use strict';
import path from 'path';
import glob from 'glob';
import browserify from 'browserify';
import watchify from 'watchify';
import envify from 'envify';
import babelify from 'babelify';
import _ from 'lodash';
import vsource from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import gulpif from 'gulp-if';
export default function(gulp, plugins, args, config, taskTarget, browserSync) {
let dirs = config.directories;
let entries = config.entries;
let browserifyTask = (files) => {
return files.map((entry) => {
let dest = path.resolve(taskTarget);
// Options
let customOpts = {
entries: [entry],
debug: true,
transform: [
babelify, // Enable ES6 features
envify // Sets NODE_ENV for better optimization of npm packages
],
paths: ['./node_modules','./src/_modules/', './src/Cwp/assets/PTM/scripts/', './src/_Cwp/assets/PTM/scripts/']
};
let bundler = browserify(customOpts);
if (!args.production) {
// Setup Watchify for faster builds
let opts = _.assign({}, watchify.args, customOpts);
bundler = watchify(browserify(opts));
}
let rebundle = function() {
let startTime = new Date().getTime();
bundler.bundle()
.on('error', function(err) {
plugins.util.log(
plugins.util.colors.red('Browserify compile error:'),
'\n',
err.stack,
'\n'
);
this.emit('end');
})
.on('error', plugins.notify.onError(config.defaultNotification))
.pipe(vsource(entry))
.pipe(buffer())
.pipe(plugins.sourcemaps.init({loadMaps: true}))
.pipe(gulpif(args.production, plugins.minify()))
.on('error', plugins.notify.onError(config.defaultNotification))
.pipe(plugins.rename(function(filepath) {
// Remove 'source' directory as well as prefixed folder underscores
// Ex: 'src/_scripts' --> '/scripts'
filepath.dirname = filepath.dirname.replace(dirs.source, '').replace('_', '');
}))
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest(dest))
// Show which file was bundled and how long it took
.on('end', function() {
let time = (new Date().getTime() - startTime) / 1000;
console.log(
plugins.util.colors.cyan(entry)
+ ' was browserified: '
+ plugins.util.colors.magenta(time + 's'));
return browserSync.reload('*.js');
});
};
if (!args.production) {
bundler.on('update', rebundle); // on any dep update, runs the bundler
bundler.on('log', plugins.util.log); // output build logs to terminal
}
return rebundle();
});
};
// Browserify Task
gulp.task('browserify', (done) => {
return glob('./' + path.join(dirs.source, dirs.scripts, entries.js), function(err, files) {
if (err) {
done(err);
}
return browserifyTask(files);
});
});
}
When I execute gulp build in my terminal, below output is:
C:\Users\Chan\Downloads\Frontend\Frontend>gulp build
[23:25:23] Requiring external module babel-register
[23:25:25] Using gulpfile ~\Downloads\Frontend\Frontend\gulpfile.babel.js
[23:25:25] Starting 'browserify'...
[23:25:26] 842639 bytes written (1.21 seconds)
[23:25:27] 831961 bytes written (1.55 seconds)
./src/_Cwp/assets/PTM/scripts/main-contribute-form-iframe.js was browserified: 1.751s
./src/_Cwp/assets/PTM/scripts/main-vip-tree-iframe.js was browserified: 1.607s
[23:25:27] 1445674 bytes written (1.76 seconds)
./src/_Cwp/assets/PTM/scripts/main-plot-tree-iframe.js was browserified: 1.853s
[23:25:31] 7046431 bytes written (5.32 seconds)
./src/_Cwp/assets/PTM/scripts/main.js was browserified: 5.589s
The terminal looks stucked. what seems to be the problem here?

Node JS can't find module

I have a files.js file and am requiring it at the start of my code.
When I use:
const files = require('./lib/files');
I get this error:
Error: Cannot find module './lib/files'
However if I test it with another one of the files in the same folder like:
const files = require('./lib/repo');
It runs.
files.js:
const fs = require('fs');
const path = require('path');
module.exports = {
getCurrentDirectoryBase: () => {
return path.basename(process.cwd());
},
directoryExists: (filePath) => {
return fs.existsSync(filePath);
}
};
I would use tree command however I have too many node modules installed to show it correctly so:
const { getCurrentDirectoryBase, directoryExists } = require('./lib/files')

gulp-install not install the dependencies with vinyl file

I'm a beginner of gulp plugin. I want install dependencies by merged package.json. The code as follow.
gulp.task('install-dependencies', function () {
var through = require('through2');
var npm = require('npm');
var Promise = require('bluebird');
var file = require('gulp-file');
var install = require('gulp-install');
var path = require('path');
var npmLoad = Promise.promisify(npm.load);
var plugins = {};
//for test
var lastFile;
gulp.src([`${PATH.plugin}**/package.json`])
.pipe(through.obj(function parse_plugins(file, enc, cb) {
if (file.isNull()) {
cb();
return;
}
if (file.isStream()) {
this.emit('error', new gulpUtil.PluginError('package-concat', 'Streaming not supported'));
cb();
return;
}
let fileContent = {};
try {
fileContent = JSON.parse(file.contents.toString())
} catch (e) {
this.emit('error', new gulpUtil.PluginError('package-concat', `file '${file.path}' not a json file!`));
throw e;
}
plugins = Object.assign({}, plugins, fileContent.dependencies)
lastFile = file;
cb();
},
function install(cb){
let fileContent = {};
fileContent.name = "test";
fileContent.dependencies = plugins;
var file = new gulpUtil.File({
base: path.join(__dirname, './'),
cwd: __dirname,
path: path.join(__dirname, './package.json'),
contents: new Buffer(JSON.stringify(fileContent))
});
this.push(file);
cb();
}
))
.pipe(install());
})
But, The dependencies not install as expected. And the log as follow.
[14:50:37] Starting 'install-dependencies'...
[14:50:37] Finished 'install-dependencies' after 205 ms
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents#1.0.11
What is your operating system ?
You might find something similar here.
Sounds like you can try to uninstall everything and start again from scratch (or just delete your node_module folder and use npm install). Not sure though, depends a lot on your operating system according to the error itself.

Categories

Resources