Can't specify a custom reporter in mocha options/mocharc/etc - javascript

I am trying to develop a custom reporter for mocha output that will be used with protractor. I have developed a good deal of the reporter and if I use the "--reporter" command line argument it works fine. However if I try to specify it in mocharc, or more importantly reporterOptions within the protractor configuration file it can't seem to find the package. Is the command line reporter flag the only way to specify a local/custom reporter? If not, how are you supposed to specify it outside of the command line?
.babelrc:
require:
- '#babel/polyfill'
- '#babel/register'
reporter: './mocha-reporter'
spec: '_src/js/tests/unit/**/*.spec.js'
package.json:
{
"name": "box",
"version": "1.0.0",
"description": "boom!",
"main": "index.js",
"scripts": {
"mocha": "mocha",
"mocha-custom": "mocha -O outputDir=_src/js/tests/reports,testDir=_src/js/tests/unit --reporter mocha-reporter",
"mochawesonme": "mocha --reporter mochawesome --reporter-options reportDir=_src/js/tests/reports,reportFilename=PCMS_unit_test_results",
"check-types": "tsc",
"clean-selenium": "webdriver-manager clean",
"update-selenium": "webdriver-manager update --standalone --versions.standalone=3.8.0",
"start-selenium": "webdriver-manager start --versions.standalone=3.8.0",
"integration-tests": "protractor protractor.conf.js"
},
"devDependencies": {
"#babel/cli": "~7.4.3",
"#babel/core": "~7.4.3",
"#babel/plugin-proposal-class-properties": "7.4.0",
"#babel/plugin-proposal-object-rest-spread": "~7.4.3",
"#babel/plugin-transform-destructuring": "~7.4.3",
"#babel/polyfill": "~7.4.3",
"#babel/preset-env": "~7.4.3",
"#babel/preset-typescript": "~7.3.3",
"#babel/register": "~7.4.0",
"#fortawesome/fontawesome-free": "5.8.1",
"#types/bluebird": "3.5.26",
"#types/jquery": "3.3.29",
"#types/knockout": "~3.4.65",
"#typescript-eslint/eslint-plugin": "~1.7.0",
"#typescript-eslint/parser": "~1.7.0",
"appcache-webpack-plugin": "~1.4.0",
"autoprefixer": "~9.5.1",
"babel-loader": "~8.0.5",
"chai": "~4.2.0",
"chai-as-promised": "7.1.1",
"copy-webpack-plugin": "~5.0.3",
"css-loader": "~2.1.1",
"eslint": "~5.16.0",
"eslint-config-airbnb-base": "~13.1.0",
"eslint-config-airbnb-typescript": "~3.0.0",
"eslint-plugin-import": "~2.17.2",
"file-loader": "~3.0.1",
"html-loader": "~0.5.5",
"html-webpack-plugin": "3.2.0",
"js-yaml": "~3.13.1",
"json-loader": "~0.5.7",
"jszip": "~3.2.1",
"karma": "~4.1.0",
"karma-chai": "~0.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-firefox-launcher": "~1.1.0",
"karma-mocha": "~1.3.0",
"karma-sinon": "~1.0.5",
"karma-webpack": "~3.0.5",
"mini-css-extract-plugin": "~0.6.0",
"mocha": "~6.1.4",
"mocha-reporter": "file:mocha-reporter",
"mochawesome": "~3.1.2",
"mochawesome-report-generator": "3.1.5",
"mochawesome-screenshots": "1.6.0",
"node-sass": "^4.12.0",
"popper.js": "~1.15.0",
"postcss-loader": "~3.0.0",
"protractor": "5.4.2",
"protractor-image-comparison": "3.1.0",
"sass-loader": "~7.1.0",
"sinon": "~7.3.2",
"style-loader": "~0.23.1",
"typescript": "~3.4.5",
"url-loader": "~1.1.2",
"webpack": "~4.30.0",
"webpack-cli": "~3.3.1",
"webpack-dev-server": "~3.3.1"
},
"dependencies": {
"bluebird": "~3.5.4",
"bootstrap": "3.3.7",
"d3": "~5.9.2",
"isomorphic-fetch": "2.2.1",
"jquery": "^3.4.0",
"jquery-ui": "~1.12.1",
"knockout": "~3.5.0",
"knockout-mapping": "~2.6.0",
"lodash": "~4.17.11",
"numeral": "~2.0.6",
"page": "~1.11.4"
}
}
index.js:
import mochaBaseReporter from 'mocha/lib/reporters/base';
import { takeScreenShot } from './javascript/screenShots';
import { populateTestResults } from './javascript/testTree';
import {
getFileContents,
writeToOutputFile,
} from './javascript/fileSystemAccess';
import {
getTemplate,
parseTestsIntoOutput,
addValuesToTemplate,
} from './javascript/templating';
import {
SUCCESS,
FAILURE,
FINISHED,
} from './constants';
const addStyle = template => getFileContents('styles.css')
.then(styles => addValuesToTemplate(template, { styles }))
.catch(error => console.log('file read of styles.css failed', error));
const createReport = (outputDirectory, fileName, data) => getTemplate('report')
.then(template => addValuesToTemplate(template, { 'test-suites': data }))
.then(template => writeToOutputFile(outputDirectory, `${fileName}.html`, template))
.catch(error => console.log('file read of template.html failed', error));
function mochaReporter(runner, environment) {
const tests = {};
const fileName = 'testfile';
const { outputDir, testDir, takeScreenShotOnFailure } = environment.reporterOptions || {};
const outputDirectory = outputDir && `${process.cwd()}/${outputDir}`;
const accumulateTestResults = (test, image) => populateTestResults(test, testDir, tests, image);
mochaBaseReporter.call(this, runner);
runner.on(SUCCESS, accumulateTestResults);
runner.on(FAILURE, test => (
takeScreenShotOnFailure && window
? takeScreenShot()
: Promise.resolve()
).then(image => accumulateTestResults(test, image)));
runner.on(FINISHED, () => {
parseTestsIntoOutput(tests)
.then(addStyle)
.then(template => addValuesToTemplate(template, runner.stats))
.then(html => createReport(outputDirectory, fileName, html))
.then(() => writeToOutputFile(
`${outputDirectory}/history`,
`test-run-${Date.now()}.json`,
JSON.stringify(tests),
));
});
return runner;
}
module.exports = mochaReporter;
protractor.conf:
/* eslint-disable global-require */
/* eslint-disable #typescript-eslint/no-var-requires */
const protractor = require('protractor');
const { join } = require('path');
const testDirectory = '_src/js/tests';
const baseDirectory = `${testDirectory}/integration/`;
// specifies whether tests will be run in parralel or not
const shardTestFiles = true;
// specifies how many browsers/drivers may be run in parralel
const maxInstances = 4;
function onPrepare() {
// register typescript file extensions with the babel compiler
require('#babel/register')({ extensions: ['.js', '.ts'] });
require('#babel/polyfill');
// don't wait for angular (since our app is currently not angular)
protractor.browser.waitForAngularEnabled(false);
// hot fix for protractor strange map behavior
// found here: https://github.com/angular/protractor/issues/2227#issuecomment-337249891
protractor.ElementArrayFinder.prototype.map = function mapHotFix(mapFn) {
return this.reduce((arr, el) => arr.concat(mapFn(el, arr.length)), []);
};
}
exports.config = {
// mocha configuration
framework: 'mocha',
mochaOpts: {
reporter: './mocha-reporter',
reporterOptions: {
outputDir: `${testDirectory}/reports`,
testDir: `${baseDirectory}/endToEnd`,
takeScreenShotOnFailure: true,
},
timeout: 600000,
slow: 3000,
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// turn off promise management in favor of async/await
SELENIUM_PROMISE_MANAGER: false,
// spec config
specs: [`${baseDirectory}/endToEnd/**/*.spec.js`],
// browser configuration
timeout: 100000,
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles,
maxInstances,
chromeOptions: {
args: [
// 'show-fps-counter=true',
'--headless',
// '--disable-gpu',
'--window-size=1300,1000',
],
},
},
{
browserName: 'firefox',
shardTestFiles,
maxInstances,
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
],
onPrepare,
plugins: [
{
package: 'protractor-image-comparison',
options: {
baselineFolder: join(process.cwd(), `${baseDirectory}/screenshots/baseline/`),
screenshotPath: join(process.cwd(), `${baseDirectory}/screenshots/tmp/`),
formatImageName: '{tag}-{logName}-{width}x{height}',
savePerInstance: true,
autoSaveBaseline: true,
},
},
],
};

I could not find a way to load the local file directly, however I gave it a package.json and installed it directly to node_modules with npm. To be specific I ran
npm install ./mocha-reporter --save-dev
on my project directory after creating a package.json within the project folder. After some debugging I was able to solve my issue since the package was now a part of node's named packages.

Related

How to solve [webpack-cli] Failed to load ? [ERR_REQUIRE_ESM]

I Started learning THREEJS but every time I execute npm run dev the following error comes up and I can't figure out what is wrong with my npm . node v18.7.0
I am learning this course from Threejs journey and the starter pack they gave and told me to run the commands in the terminal I am encountering the error mentioned below
I have no idea how to fix this.
Error
[webpack-cli] Failed to load 'D:\3js\l2\04-webpack\bundler\webpack.dev.js' config
[webpack-cli] Error [ERR_REQUIRE_ESM]: require() of ES Module D:\3js\l2\04-webpack\node_modules\internal-ip\index.js from D:\3js\l2\04-webpack\bundler\webpack.dev.js not supported.
Instead change the require of index.js in D:\3js\l2\04-webpack\bundler\webpack.dev.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (D:\3js\l2\04-webpack\bundler\webpack.dev.js:4:12)
at async Promise.all (index 0)
at async WebpackCLI.tryRequireThenImport (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:254:18)
at async WebpackCLI.createCompiler (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:2185:18)
at async Command.<anonymous> (D:\3js\l2\04-webpack\node_modules\#webpack-cli\serve\lib\index.js:98:30)
at async Promise.all (index 1)
at async Command.<anonymous> (D:\3js\l2\04-webpack\node_modules\webpack-cli\lib\webpack-cli.js:1672:7) {
code: 'ERR_REQUIRE_ESM'
}
package.json
{
"repository": "#",
"license": "UNLICENSED",
"scripts": {
"build": "webpack --config ./bundler/webpack.prod.js",
"dev": "webpack serve --config ./bundler/webpack.dev.js"
},
"dependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-loader": "^8.2.3",
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^9.0.1",
"css-loader": "^6.5.0",
"file-loader": "^6.2.0",
"html-loader": "^3.0.0",
"html-webpack-plugin": "^5.5.0",
"internal-ip": "^7.0.0",
"mini-css-extract-plugin": "^2.4.3",
"portfinder-sync": "0.0.2",
"raw-loader": "^4.0.2",
"style-loader": "^3.3.1",
"three": "^0.134.0",
"webpack": "^5.60.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0",
"webpack-merge": "^5.8.0"
}
}
webpack.dev.js
const path = require('path')
const { merge } = require('webpack-merge')
const commonConfiguration = require('./webpack.common.js')
const ip = require('internal-ip')
const portFinderSync = require('portfinder-sync')
const infoColor = (_message) =>
{
return `\u001b[1m\u001b[34m${_message}\u001b[39m\u001b[22m`
}
module.exports = merge(
commonConfiguration,
{
stats: 'errors-warnings',
mode: 'development',
devServer:
{
host: 'local-ip',
port: portFinderSync.getPort(8080),
open: true,
https: false,
allowedHosts: 'all',
hot: false,
watchFiles: ['src/**', 'static/**'],
static:
{
watch: true,
directory: path.join(__dirname, '../static')
},
client:
{
logging: 'none',
overlay: true,
progress: false
},
onAfterSetupMiddleware: function(devServer)
{
const port = devServer.options.port
const https = devServer.options.https ? 's' : ''
const localIp = ip.v4.sync()
const domain1 = `http${https}://${localIp}:${port}`
const domain2 = `http${https}://localhost:${port}`
console.log(`Project running at:\n - ${infoColor(domain1)}\n - ${infoColor(domain2)}`)
}
}
}
)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
import path from 'path'
import { merge } from 'webpack-merge'
import commonConfiguration from './webpack.common.js'
import ip from 'internal-ip'
import portFinderSync from 'portfinder-sync'

Vue Js not deploying to Firebase because of Eslint Error

I am getting this error for the past hours and i have not been able to resolve it. I have tried all the solutions online including uninstalling aslant globally and in the project and installing it again. Unfortunately the most common answer does not really apply in my case since my package.json file does not really have that file structure.
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint .
/Users/KingdomMac/Downloads/ermnl-dashboard-master/functions/index.js
22:71 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
Error: functions predeploy error: Command terminated with non-zero exit code1
My package.json file
{
"name": "vue-white-dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-brands-svg-icons": "^5.15.3",
"#fortawesome/free-regular-svg-icons": "^5.15.3",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/vue-fontawesome": "^2.0.2",
"axios": "^0.21.1",
"chart.js": "^2.8.0",
"core-js": "^2.6.5",
"firebase": "^8.6.8",
"node-sass": "^4.9.0",
"vue": "^2.6.10",
"vue-chartjs": "^3.4.2",
"vue-click-outside": "^1.0.7",
"vue-clickaway": "^2.2.2",
"vue-github-buttons": "^3.1.0",
"vue-i18n": "^8.14.1",
"vue-router": "^3.0.3",
"vue-social-sharing": "^2.4.6",
"vue2-transitions": "^0.3.0",
"vuetify": "^2.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.11.0",
"#vue/cli-plugin-eslint": "^3.1.1",
"#vue/cli-service": "^3.5.3",
"#vue/eslint-config-prettier": "^5.0.0",
"babel-eslint": "^10.0.1",
"eslint": "^8.1.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-vue": "^7.20.0",
"prettier": "^1.18.2",
"sass": "~1.32",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.4.1",
"vue-template-compiler": "^2.6.10",
"vuetify-loader": "^1.7.0"
}
}
Also my .eslintrc.js file
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "plugin:vue/essential",
"parserOptions": {
"ecmaVersion": 13
},
"plugins": [
"vue"
],
"rules": {
}
};
And my index.js file
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// exports.addAdminRole = functions.https.onCall((data, context) => {
// // Get user and add custom claim (admin)
// const customClaims = {
// admin: true,
// };
// return admin.auth().getUserByEmail(data.email).then((user) => {
// return admin.auth().setCustomUserClaims(user.uid, customClaims);
// }).then((authUser) => {
// return {
// message: `Success! ${data.email} has been made an admin.`,
// };
// }).catch((error) => {
// return error;
// });
// });
exports.addUserRole = functions.auth.user().onCreate(async (authUser) => {
if (authUser.email) {
const customClaims = {
admin: true,
};
try {
let _ = await admin.auth().setCustomUserClaims(authUser.uid, customClaims);
return db.collection("roles").doc(authUser.uid).set({
email: authUser.email,
role: customClaims,
});
} catch (error) {
console.log(error);
}
}
});
exports.setUserRole = functions.https.onCall(async (data, context) => {
if (!context.auth.token.admin) return
try {
let _ = await admin.auth().setCustomUserClaims(data.uid, data.role)
return db.collection("roles").doc(data.uid).update({
role: data.role
})
} catch (error) {
console.log(error)
}
});
try changing "lint": "eslint ." to "lint": "eslint ", in your package.json

Gulp 3.9 + Browserify 11.2 to Gulp 4.0 + Browserify 17.0

I'm trying to update an old repository that is using Gulp 3.9.1 + browserify 11.2.0 to Gulp 4.0.2 + browserify 17.0.0. But those are not the only packages I'm using in this project.
This is the old package.json and the old code I'm trying to port to the new version:
package.json:
"devDependencies": {
"babel": "^5.8.29",
"babel-cli": "^6.22.2",
"babel-preset-es2015": "^6.22.0",
"babelify": "^6.4.0",
"browserify": "^11.2.0",
"core-js": "^1.2.3",
"extend": "^3.0.0",
"fs": "0.0.2",
"glslify": "^2.3.1",
"gsap": "^1.18.0",
"gulp": "^3.9.1",
"gulp-babel": "^5.2.1",
"gulp-connect": "^2.2.0",
"gulp-imagemin": "^3.1.1",
"gulp-newer": "^1.3.0",
"gulp-streamify": "^1.0.2",
"gulp-uglify": "^1.5.3",
"uglify-js": "^2.5.0",
"vinyl-source-stream": "^1.1.0"
}
Code:
const gulp = require('gulp')
const source = require('vinyl-source-stream')
const browserify = require('browserify')
const uglify = require('gulp-uglify')
const streamify = require('gulp-streamify')
const babelify = require("babelify");
gulp.task('build', function(){
build();
});
function build() {
browserify('src/index.js', {debug: true})
.transform(babelify)
.transform('glslify')
.bundle()
.on('error', function (err) {
console.log('Error : ' + err.message);
})
.pipe(source('index.min.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest('public/js'));
}
The new package.json and the code I have until now, that I'm not sure if it is the correct implementation:
package.json:
"devDependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.18.0",
"babel-preset-env": "^1.7.0",
"browserify": "^17.0.0",
"core-js": "^1.2.3",
"extend": "^3.0.0",
"fs": "0.0.2",
"glslify": "^7.1.1",
"gsap": "^3.6.1",
"gulp": "^4.0.2",
"gulp-babel": "^8.0.0",
"gulp-connect": "^2.2.0",
"gulp-imagemin": "^7.1.0",
"gulp-map": "^0.0.2",
"gulp-newer": "^1.3.0",
"gulp-streamify": "^1.0.2",
"gulp-uglify": "^1.5.3",
"uglify-js": "^2.5.0",
"vinyl": "^0.5.3",
"vinyl-source-stream": "^1.1.0"
}
Code:
const gulp = require('gulp');
const browserify = require('browserify');
const babel = require('gulp-babel');
const glslify = require('glslify')
const source = require('vinyl-source-stream');
const streamify = require('gulp-streamify');
const uglify = require('gulp-uglify');
const map = require('gulp-map');
const Vinyl = require('vinyl');
gulp.task(build)
function build() {
gulp.src(['./src/**/*.js', './src/**/*.jsx'])
.pipe(browserify()
.transform(babel({options: 'env'}))
//.transform(glslify('./src/shaders/simple.vert')) // Not working
//.transform(glslify('./src/shaders/water.frag')) // Not working
.bundle().on('error', onError))
.pipe(source('index.min.js'))
.pipe(streamify(uglify()))
.pipe(map(function(file) {
// Explicitly convert to Vinyl object otherwise `gulp.dest()` will fail
return new Vinyl(file); // But it stills failing
}))
.pipe(gulp.dest('./public/js/'));
}
function onError(err) {
console.log('Error : ' + err.message);
}
I'm not sure if that is the correct way to migrate that code. I'm getting several issues from the different browserify modules, for example:
babel: that it seems to be fixed by changing from babelify to gulp-bable
glslify: that it seems to be deprecated, but I don't know which is the replace library
Also, and sorry for being repetitive, as I don't know how the migration should be, I'm getting this error after running the build command (gulp build):
[14:08:34] Using gulpfile ~/Documents/workspace/project/gulpfile.js
[14:08:34] Starting 'build'...
[14:08:34] 'build' errored after 109 ms
[14:08:34] TypeError: dest.write is not a function
at DestroyableTransform.ondata (/Users/user/Documents/workspace/project/node_modules/readable-stream/lib/_stream_readable.js:619:20)
at DestroyableTransform.emit (node:events:379:20)
at DestroyableTransform.EventEmitter.emit (node:domain:532:15)
at addChunk (/Users/user/Documents/workspace/project/node_modules/readable-stream/lib/_stream_readable.js:291:12)
at readableAddChunk (/Users/user/Documents/workspace/project/node_modules/readable-stream/lib/_stream_readable.js:278:11)
at DestroyableTransform.Readable.push (/Users/user/Documents/workspace/project/node_modules/readable-stream/lib/_stream_readable.js:245:10)
at DestroyableTransform.Transform.push (/Users/user/Documents/workspace/project/node_modules/readable-stream/lib/_stream_transform.js:148:32)
at Pumpify.onReadable (/Users/user/Documents/workspace/project/node_modules/to-through/index.js:25:14)
at Pumpify.emit (node:events:379:20)
at Pumpify.EventEmitter.emit (node:domain:532:15)
Sorry for the long explanation, hope someone can help me.
After a lot of researching, I found this blog which has the answer, or almost it has the links to the answer.
One of the links took me to the most detailed tutorial about Gulp + Browserify + Babelify it could ever exist. Here the link. These are a serie of tutorial explaining how to implement Gulp from Scratch. If you don't want to see the videos and just want the code go here.
This is my final gulpfile.js.
And this is the answer to my question:
My formerly build function in gulpfile.js (now called js)
function js(done) {
jsFiles.map( function( entry ) {
return browserify({
entries: [constants.jsSRC + entry] // constants.jsSRC == "./src/js/"
})
.transform( babelify, { presets: [ '#babel/preset-env' ] } )
.transform('glslify')
.bundle()
.pipe(source( entry ) )
.pipe(rename( {
extname: '.min.js'
}))
.pipe(buffer() )
.pipe(gulpif( options.has( 'production' ), stripDebug() ) )
.pipe(sourcemaps.init({ loadMaps: true }) )
.pipe(uglify())
.pipe(sourcemaps.write( '.' ))
.pipe(dest(constants.jsURL)) // constants.jsURL == "./dist/js/"
.pipe(browserSync.stream());
});
done();
}
The task inside the same file gulpfile.js
task("js", js);
My package.json file.
...
"devDependencies": {
"#babel/core": "^7.13.14",
"#babel/preset-env": "^7.13.12",
"babelify": "^10.0.0",
"browser-sync": "^2.26.14",
"browserify": "^17.0.0",
"browserify-shim": "^3.8.14",
"core-js": "^1.2.3",
"glslify": "^7.1.1",
"gsap": "^3.6.1",
"gulp": "^4.0.2",
"gulp-connect": "^2.2.0",
"gulp-if": "^3.0.0",
"gulp-notify": "^3.2.0",
"gulp-options": "^1.1.1",
"gulp-plumber": "^1.2.1",
"gulp-rename": "^2.0.0",
"gulp-sourcemaps": "^3.0.0",
"gulp-strip-debug": "^4.0.0",
"gulp-uglify": "^1.5.3",
"gulp-uglifycss": "^1.1.0",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0"
},
"babel": {
"presets": [
"#babel/preset-env"
]
},
"browserify": {
"transform": [
"browserify-shim"
]
},
...
Note that there is a babel section and a browserify section that are also needed.
And to run that gulp task simply do:
gulp js
One last thing, the example of the tutorials (thank you Alessandro Castellani) and my final solution, are mostly the same and also contain the other tasks to process the css files, the fonts, the images, and the html file. All of those files are moved to a "production" folder, in my case called dist.

Webpack creating separate JS files for few imports

I am trying to build a custom webpack configuration for a complex project. While building I have observed that webpack is generating separate JS file when I import babel-runtime/core-js/json/stringify. Can someone help me understand what's happening here and why webpack is generating a separate JS file.
package.json
{
"name": "react-boilerplate",
"version": "1.0.0",
"description": "A boilerplate for large scale react apps",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development",
"build": "sh -ac 'webpack --mode production ${DEPLOY_TARGET:+--env.target $DEPLOY_TARGET}'",
"build:production": "DEPLOY_TARGET='production' yarn build",
"build:staging": "DEPLOY_TARGET='staging' yarn build"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.3",
"#babel/preset-react": "^7.6.3",
"#typescript-eslint/eslint-plugin": "2.x",
"#typescript-eslint/parser": "2.x",
"babel-eslint": "10.x",
"babel-loader": "^8.0.6",
"babel-preset-react-app": "^9.0.2",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"dotenv": "^8.2.0",
"eslint": "6.x",
"eslint-config-react-app": "^5.0.2",
"eslint-loader": "^3.0.2",
"eslint-plugin-flowtype": "3.x",
"eslint-plugin-import": "2.x",
"eslint-plugin-jsx-a11y": "6.x",
"eslint-plugin-react": "7.x",
"eslint-plugin-react-hooks": "1.x",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"react-hot-loader": "^4.12.15",
"stylelint": "^11.1.1",
"stylelint-config-standard": "^19.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-custom-processor-loader": "^0.6.0",
"stylelint-processor-styled-components": "^1.8.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2",
"webpack-merge": "^4.2.2",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"lodash": "^4.17.15",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
},
"peerDependencies": {
"stylelint": "^11.1.1"
}
}
webpack.config.js
const { DefinePlugin } = require('webpack');
const path = require('path');
// Webpack plugins
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWepackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { rootDir } = require('./utils');
const {
entryPath,
getEnvJson,
htmlTemplatePath,
outputDir,
publicDir,
sourceDir,
} = require('./utils');
module.exports = env => ({
// Configure's our app entry points
entry: {
main: entryPath,
},
// Configure's loaders to let webpact know how different extension should be
// loaded when bundling
module: {
rules: [
// Configure's babel loader for transpiling javascript, eslint loader
// for linting javascript, stylelint loader for css linting
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'stylelint-custom-processor-loader',
options: {
configPath: path.resolve(rootDir, '.stylelintrc.js'),
},
},
'eslint-loader',
]
},
// Configure's loaders for images
{
test: /.(png|jpg|jpeg|svg|gif)/,
use: 'file-loader'
},
]
},
// Configure's destination for the bundled code
output: {
path: outputDir,
},
// Configure's additions plugins to be used by webpack
// Order of plugins is important
plugins: [
// Removes all the contents of output folder(but not the folder itself)
// before every webpack build
new CleanWebpackPlugin(),
// Copies all contents of public folder as it is excluding index.html file
new CopyWepackPlugin([
{
from: publicDir,
to: outputDir,
ignore: ['index.html']
}
]),
// Injects target specific enviroment variables
new DefinePlugin({
'process.env': getEnvJson(env.target)
}),
// Uses `public/index.html` and creates a `index.html` file for the app
// by injecting the generated bundles javascript files
new HtmlWebpackPlugin({
template: htmlTemplatePath
}),
],
// Configure's custom behavior for how modules are resolved by webpack
resolve: {
modules: [sourceDir, 'node_modules']
}
});
.babelrc
{
"presets": ["react-app"]
}
That is because of your entryPath.
module.exports = {
entry: {
bundle1: '.src/fileForBundle1.js',
bundle2: '.src/fileForBundle2.js'
},
This would generate two bundles.
Make sure entryPath is not an object of multiple values.
Issue was with the file-loader regex which was incorrectly configured and which resulted in matching babel-runtime/core-js/json/stringify. So file-loader was being used to load it.

Writing tests with karma/jasmine

I have been building normal js apps using frameworks like ember/angular. They already have everything built in for compilation and testing.
I started building an app in vanilla js. I wrote code in es6.
I started with tests using karma/jasmine. I got stuck with the configuration. I went through couple of articles and got a little success but again got stuck in relative error from browserify in karma. ERROR [framework.browserify]: Error: Cannot find module
How can I write tests with karma/jasmine. What to use? webpack/browserify?
My app structure is:
app/js/**/*.js app/tests/**/*.js app/css/**.css app/index.html app/Gruntfile.js app/karma.conf.js app/package.json app/server.js
This is my gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
browserify: {
development: {
src: [
"./js/application.js",
],
dest: './js/common.js',
options: {
browserifyOptions: {
debug: true
},
transform: [
["babelify", {
"presets": ["es2015"]
}]
]
}
}
},
watch: {
scripts: {
files: ["./js/**/*.js"],
tasks: ["browserify"]
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-watch');
};
This is karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
browsers: ['Chrome'],
files: [
'js/**/*.js',
'tests/**/*.js'
],
exclude: [],
preprocessors: {
'js/**/*.js': ['browserify'],
'tests/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify']
},
reporters: ['progress', 'html'],
// the default configuration
htmlReporter: {
outputDir: 'karma_html', // where to put the reports
templatePath: null, // set if you moved jasmine_template.html
focusOnFailures: true, // reports show failures on start
namedFiles: false, // name files instead of creating sub-directories
pageTitle: null, // page title for reports; browser info by default
urlFriendlyName: false, // simply replaces spaces with _ for files/dirs
reportName: 'report-summary-filename', // report summary filename; browser info by default
// experimental
preserveDescribeNesting: false, // folded suites stay folded
foldAll: false, // reports start folded (only with preserveDescribeNesting)
}
});
};
This is my package.json
{
"author": "Yomn",
"name": "myapp",
"version": "0.0.0",
"scripts": {
"start": "node server.js",
"tests": "karma start"
},
"devDependencies": {
"babel-core": "^5.0.0",
"babel-loader": "^5.0.0",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^14.4.0",
"grunt": "^1.0.1",
"grunt-browserify": "^5.1.0",
"grunt-contrib-watch": "^1.0.0",
"jasmine": "^2.2.1",
"jasmine-core": "^2.2.0",
"karma": "^0.13.2",
"karma-browserify": "~3.0.2",
"karma-chrome-launcher": "^2.2.0",
"karma-html-reporter": "^0.2.7",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^1.0.4",
"karma-webpack": "^1.6.0",
"phantomjs-prebuilt": "^2.1.15",
"webpack": "^1.8.4"
}
}
I tried to run project with your configuration, but since you did not provide examples of the files, I sketched out my example that works. I hope it will be useful.
js\Circle.js:
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}
exports.Circle = Circle;
tests\Circle.js:
var Circle = require('../js/Circle');
describe('Circle', () => {
describe(`constructor`, () => {
it(`should initialize properties correctly`, () => {
const circle = new Circle.Circle(1, 2, 3);
expect(circle.x).toBe(1);
});
});
});
Karma start command: "node_modules\.bin\karma" start --no-single-run

Categories

Resources