I set up a react jsx project with a front end. I am trying to use playwright as a web crawler and on the click of a button on the front end I am trying to execute playwright scripts. I generated this file (sample.js) for testing purposes
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({
headless: false
});
const context = await browser.newContext();
// Open new page
const page = await context.newPage();
await page.goto('https://google.com');
// ---------------------
await context.close();
await browser.close();
})();
There are 2 approaches I tried.
Approach 1. I tried to turn it into a file with a method I can call from some other js file
import { chromium } from 'playwright';
const AutomationUtil = {
testCall2: async () => {
console.log('testing testCall async')
}
}
export default AutomationUtil
but the moment I add the first line: "import { chromium } from 'playwright';" it winds up trying to read a html file in node_modules/playwright and gives me the following error:
ERROR in ./node_modules/playwright-core/lib/webpack/recorder/index.html 1:0
Module parse failed: Unexpected token (1:0)
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
> <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Playwright Inspector</title><script defer="defer" src="app.bundle.js"></script></head><body><div id="root"></div></body></html>
even when I install html loader and set up the rule in webpack.config.js
module.exports = {
resolve: {
fallback: {
path: false ,
buffer: false,
util: false,
stream: false,
constants: false,
fs: false
},
rules: [
{
test: /\.html$/,
loader: "html-loader",
use: ["html-loader"],
},
{
loader: 'babel-loader',
test: /\.js|\.jsx$/,
exclude: /node_modules/,
},
],
loaders: [
{
test: /\.html$/,
loader: "html-loader",
},
],
}
}
it gives me the same error
Approach 2. I found that if I run node sample.js in the terminal it successfully executes the playwright script. So I tried using child process execSync to run a terminal command when the button on the front end is clicked
testClick2 = () => {
// AutomationUtil.testCall2()
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' }); // node sample.js will replace 'ls'
console.log('Output was:\n', output);
}
however, this gives me a Uncaught TypeError: execSync is not a function even though when I check in playwright, it is listed as a function. I tried other stackoverflow suggestions to try it with exec and it gives me the same type of error