Feature files require some loader file to run - javascript

I'm trying to run the Feature file using cucumber in Cypress 10.2.0.
It is throwing me an issue of "WebPack Compilation Error"
Error: Webpack Compilation Error
./cypress/e2e/BankManagerLogin.feature 1:14
Module parse failed: Unexpected token (1:14)
You may need an appropriate loader to handle this file type, currently, no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
any help would be appreciated

The cypress.config file needs adjusting to clear that error.
Try this, it's bolier-plate code from the badeball repository.
This assumes you have Typescript (let me know if you're only using Javascript).
import { defineConfig } from "cypress";
import * as webpack from "#cypress/webpack-preprocessor";
import { addCucumberPreprocessorPlugin } from "#badeball/cypress-cucumber-preprocessor";
async function setupNodeEvents(
on: Cypress.PluginEvents,
config: Cypress.PluginConfigOptions
): Promise<Cypress.PluginConfigOptions> {
await addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
webpack({
webpackOptions: {
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
exclude: [/node_modules/],
use: [
{
loader: "ts-loader",
},
],
},
{
test: /\.feature$/,
use: [
{
loader: "#badeball/cypress-cucumber-preprocessor/webpack",
options: config,
},
],
},
],
},
},
})
);
// Make sure to return the config object as it might have been modified by the plugin.
return config;
}
export default defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});

Related

Cypress for Components Tests React configuration problem absolute path

the goal is to use Cypress for component testing and e2e testing mainly.
Install and configure all Cypress correctly, configure Cypress in the 'cypress open' script to open E2E related tests and configure the 'cypress open-ct' script for component tests, all settings work very well.
Problem
The project is already ready and I have absolute folders configuration, when I import a component from '~/components' I am accessing 'src/components', I am not able to make the proper settings to be able to access the absolute folders because when I run the cypress open script -ct doesn't seem to run 'file:preprocessor', where you need to run it to run the webpack where you have the absolute folder settings.
I tried several alternatives and this was the one that worked the best because when I run the 'cypress open' script cypress executes 'file:preprocessor' it applies the webpack settings and if I try to import a component using '~/component/InputDate' it works , however 'cypress open' is for E2E tests, I can't run unit tests through this script.
I can be wrong about the cypress open script not running component tests correctly but I'm looking for a solution to the big problem that is these absolute folders.
Attempts
I tried the tsconfig.json files configuration solution but I couldn't make it work because I use it in the jsconfig.json project, I tried to use tsconfig.json I used the 'tsconfig-paths' package and got no result.
cypress/plugins/index.js
const webpack = require('#cypress/webpack-preprocessor')
const injectDevServer = require('#cypress/react/plugins/react-scripts')
module.exports = (on, config) => {
const options = {
webpackOptions: require('../../webpack.config.js'),
watchOptions: {},
}
on('file:preprocessor', webpack(options))
injectDevServer(on, config)
return config
}
cypress.json
{
"component": {
"componentFolder": "src/tests/components"
},
"integrationFolder": "src/tests/integration"
}
webpackconfig.js
var path = require('path')
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.js$|jsx/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
],
},
],
},
resolve: {
alias: {
'~': path.resolve(__dirname, 'src'),
},
},
}
packjage.json
"devDependencies": {
"#cypress/react": "5.12.4",
"#cypress/webpack-dev-server": "1.8.3",
"#cypress/webpack-preprocessor": "^5.11.1",
"#types/jwt-decode": "^3.1.0",
"babel-loader": "^8.2.3",
"cypress": "9.5.2",
"webpack-dev-server": "3.2.1"
}
I managed to do the following solution:
plugins/index.js
const { startDevServer } = require('#cypress/webpack-dev-server')
const webpackConfig = require('../../webpack.config.js')
module.exports = (on, config) => {
on('dev-server:start', async (options) =>
startDevServer({ options, webpackConfig }),
)
return config
}
cypress.json
{
"component": {
"componentFolder": "src/tests/unity"
},
"integrationFolder": "src/tests/integration"
}
webpack.config.js
var path = require('path')
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.js$|jsx/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
],
},
],
},
resolve: {
alias: {
'~': path.resolve(__dirname, 'src'),
},
},
}

Invalid or unexpected token loading css file using webpack in react project

I have a react project that uses styled components, and I'm trying to include a CSS file as part of react-image-gallery
I followed the steps to include css-loader and style-loader in my project and tried importing the file like this
import 'react-image-gallery/styles/css/image-gallery.css
and included the following in Webpack config rules
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
When running the server I'm getting the below error message
SyntaxError: Invalid or unexpected token
(function (exports, require, module, __filename, __dirname) { #charset "UTF-8";
in the above CSS file
From some googling, I understood that this is because the CSS file is included as a JS file by Webpack. But isn't that how it is supposed to be?
Addition info: I have a server side rendered app.
What am I doing wrong?
Update:
My rules look like this
A rules.ts file
import webpack from 'webpack'
const ts: webpack.RuleSetRule = {
test: /^(?!.*\.spec\.tsx?$).*\.tsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}
const img: webpack.RuleSetRule = {
test: /\.(png|jpe?g|gif|svg)$/,
use: 'file-loader',
}
const css: webpack.RuleSetRule = {
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
export default {
client: {
ts,
img,
css,
},
server: {
ts,
css,
img: { ...img, use: [{ loader: 'file-loader', options: { emitFile: false } }] },
},
}
A config file that has the following
const config: webpack.Configuration = {
context: path.join(__dirname, '../../src/client'),
resolve: {
...resolve.client,
alias: { 'react-dom': '#hot-loader/react-dom' },
},
devtool: false,
entry: {
main: ['./index.tsx'],
},
mode: 'development',
module: {
rules: [rules.client.ts, rules.client.img, rules.client.css],
},
output: output.client,
plugins: [
...plugins,
...developmentPlugins,
new ForkTsCheckerWebpackPlugin({
tsconfig: path.join(__dirname, '../../tsconfig.fork-ts-checker-webpack.plugin.json'),
}),
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['!webpack.partial.html', '!favicon.ico'],
}),
],
}
We had 4 co-workers stuck on an issue like that.
Actually, we had a plugin "nodemon-webpack-plugin", which we configured for webpack.
This plugin tried to execute files like .css as java-script files.
We finally removed this plugin, because we had an up and running mon already.

MQTT.js and Webpack - "WS is not a constructor"

I am trying to bundle one of our microservices which is using MQTT.js and I am struggling with really strange issue.
It is working fine without bundling, so ws is available in node_modules.
Stuff which I think matters:
error:
TypeError: WS is not a constructor
at WebSocketStream (dist/index.js:159329:16)
at createWebSocket (dist/index.js:147450:10)
at Object.buildBuilderBrowser (dist/index.js:147476:10)
at MqttClient.wrapper [as streamBuilder] (dist/index.js:147937:36)
at MqttClient._setupStream (dist/index.js:146471:22)
at new MqttClient (dist/index.js:146452:8)
at Function.connect (dist/index.js:147940:10)
webpack config:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const { NODE_ENV = 'production' } = process.env;
module.exports = {
entry: { index: './src/index.ts' },
mode: NODE_ENV,
target: 'node',
watch: NODE_ENV === 'development',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.js'],
},
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.ts$/,
use: [{ loader: 'ts-loader', options: { transpileOnly: true } }],
},
{
test: /(\.md|\.map)$/,
loader: 'null-loader',
},
],
},
};
Function where it happens:
createMqttClient(): MqttClient {
return mqtt.connect(this.mqttOptions.url, { ...this.mqttOptions.options });
}
The url is like: ssl://url-to-our-mqtt
Can anybody help please?
I also ran into same issue.
The problem for me was that I used
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
in webpack.config.js order to fix the shebang error that comes with mqtt.js since it is a CLI tool.
Then instead I have used
{
test: [
/node_modules[/\\]mqtt[/\\]mqtt.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]sub.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]pub.js/,
],
loader: 'shebang-loader'
},
And my problem was fixed. Do you also use mqtt/dist/mqtt.js instead of mqtt in your imports or if you do something similar to mine, the shebang-loader rule I have posted above might solve your problem.
I experienced the same with Amazon aws-iot-device-sdk-js and Microsoft azure-iot-device-mqtt which both include mqtt.
The initial issue is the build error:
ERROR in ./node_modules/mqtt/mqtt.js Module parse failed: Unexpected character '#' (1:0)
This error is caused by the package mqtt. Three files (mqtt.js, pub.js and sub.js) contain a shebang line
#!/usr/bin/env node
The solution using module replacement suggested some places
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
unfortunately changes the build error with the run time error
TypeError: WS is not a constructor
As mentioned in other answers, webpack can be configured (https://webpack.js.org/concepts/loaders/) to use the shebang loader (https://www.npmjs.com/package/shebang-loader)
TL;DR
Install shebang-loader
npm install shebang-loader --save
In webpack.config.js use the loader
module.exports = {
...
module: {
rules: [
{
test:
[
/.*mqtt\.js$/,
/.*sub\.js$/,
/.*pub\.js$/
],
use: 'shebang-loader'
}
]
}
}

cannot load html from webpack loader in reactjs

I'm very new to reactjs and webpack. I want to load html file to reactjs via using I use html-loader and webpack, but got this error
Failed to compile.
./src/test_ts.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
| <html>
| <body>
This is my webpack config
var path = require("path");
var webpack = require("webpack");
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin("common.js");
module.exports = {
entry: "./src/header.js",
output: {
path: path.resolve(__dirname, "build"),
filename: "app.bundle.js"
},
module: {
loaders: [
{
test: /\.html$/,
loader: "html"
},
{
test: /\.js$/,
loader: "babel-loader",
query: {
presets: ["es2015", "react"]
}
}
]
},
stats: {
colors: true
},
devtool: "source-map"
};
and this is where I want to load
import React from "react";
import { Button } from "reactstrap";
var htmlContent = require("./test_ts.html");
class Header extends React.Component {
render() {
return <div></div>;
}
}
export default Header;
I try to follow many tutorial but can't resolve this, what may I do wrong?
Add the following rule to your webpack.config file:
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
}
Before that install html-loader using command: npm i -D html-loader :

Setup webpack with server side rendering to load Sass files in asp.net core project

I'm using a Yeoman project template called "aspnetcore-spa", which is an ASP.net core 1 template working in conjunction with major SPA frameworks (Angular2 and React).
I created a project with Angular2.The biolerplate's code works fine and there is no problem. Once I add Sass loader to webpack.config.js and make a reference to the Sass file from any angular file.
In webpack.config.js :
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.scss$/,include:/ClientApp/, loaders: ["style", "css", "sass"] },
{ test: /\.html$/,include: /ClientApp/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];
In my component :
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-wine',
template: require('./wine.component.html'),
styles: require('./wine.component.scss')
})
export class WineComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
I have already installed npm packages pertinent to sass loader :
npm install node-sass sass-loader --save-dev
I have checked the main-server.js file in wwwroot/dist folder which is the result of webpack bundling, I saw that the .scss file is loaded and they styles are processed correctly. Once I run the app though, shows this exception which is coming from the server side rendering side:
An unhandled exception occurred while processing the request.
Exception: Call to Node module failed with error: ReferenceError: window is not defined at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:573:31 at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:568:48 at module.exports (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:590:69) at Object. (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:526:38) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30) at E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:501:22 at Object.module.exports (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:506:3) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30) at Object. (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:129:25) at webpack_require (E:\Dev\MyApp\MyAppCore\src\MyApp.Web\ClientApp\dist\main-server.js:20:30)
It's obviously because of the webpack's server-side rendering, as it's running the code on Node.js side (through ASP.net Core's Javascript Services) and there is a code that is coupled with the DOM window object which is not valid on node.
Any clues?
I managed to fix the problem, here's the web.config.js bit:
(Notice the loaders for .scss files)
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.scss$/,include:/ClientApp/, loaders: ["to-string", "css", "sass"] },
{ test: /\.html$/,include: /ClientApp/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
And in the Angular component I changed the styles to this :
(Passed an array of required css files rather than a single css file)
#Component({
selector: 'app-wine',
template: require('./wine.component.html'),
styles: [require('./wine.component.scss')]
})

Categories

Resources