Webpack Puppeteer Chromium Installation: Unable to launch browser - javascript

I'm setting up a node server to render React JSX components into images.
The server uses express, and the React components render to HTML using ReactDOMServer. I'm also using TypeScript. I bundle the whole thing using webpack. My webpack config is:
const path = require('path')
module.exports = {
entry: './src/index.tsx',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node-modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
target: 'node'
};
The html will be rendered to an image using node-html-to-image (https://github.com/frinyvonnick/node-html-to-image)
The server starts without problems, but when a request hits the server and the html should be rendered I get an error in the console.
This is the code for the server that executes:
app.post('/', (req, res) => {
const element = <User name={req.body.name} login={req.body.login}/>
const html = ReactDOMServer.renderToStaticMarkup(element)
nodeHtmlToImage({
output: './image.png',
html: html
}).then(() => console.log("image created successfully!"))
})
and the error I get is: UnhandledPromiseRejectionWarning: Error: Unable to launch browser, error message: Could not find browser revision 737027. Run "npm install" or "yarn install" to download a browser binary.
I suspect that the problem has to do with the chromium installation coming with puppeteer not being bundled correctly by webpack but I'm not sure.
EDIT: setting an explicit executablePath works, but removes the portability of my bundle.js.

Related

How to import javascript files in background.js in chrome extension using version 3

I am building a chrome extension in version 3 using firebase firestore. I have downloaded all the api in extension and I want to use importScript to fetch the api example: firebase-app.js and firebase-firestore.js. but it not working for me. The error in the console says "TypeError: Failed to execute 'importScripts' on 'WorkerGlobalScope': Module scripts don't support importScripts().".
Is 3 days now searching the net but no solution. Please any help?
Code of the issue
Here's a quick solution: in short, you will need to install webpack, which is a module bundler (it means that its main purpose is to bundle JavaScript files for usage in a browser). If you have npm already set up, you can execute this command in your project:
npm install webpack
After you have done that you can proceed to set up firebase (which, from what I can see from your image, you have already done). You will need to run another command:
npm install firebase
Continuing the setup of webpack, you will need to create a webpack.config.js file and there set the entry and the output. Again, you can find plenty of tutorials online, but here's a quick example implementation:
webpack.config.js:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'production',
entry: {
main: './src/main'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},
devServer: {
contentBase: './dist',
overlay: true,
hot: true
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'manifest.json', to: 'manifest.json' },
],
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'images', to: 'images' },
],
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'popup.html', to: 'popup.html' },
],
}),
new webpack.HotModuleReplacementPlugin()
],
};
Once you've done that, in your entry file (the entry point), you can import firebase and set it up:
main.js
import { initializeApp } from 'firebase/app';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
//...
};
const app = initializeApp(firebaseConfig);
When you run npm start, webpack will create another folder (the 'dist' folder). This folder is the chrome exstension with firebase set up!
Hope I was able to help you. If you have any questions feel free to ask!

Webpack Hot Module Replacement: Cannot find update

I've set up a Webpack project with 2 entries. I can connect to the dev server and there are no error messages. Though, when I change one of the entry files, Webpack recompiles (without any errors), the client notices and tries to fetch a JSON, wich doesn't exist. Here is the full log after connecting to the dev server:
[HMR] Waiting for update signal from WDS...
main.js:20 [WDS] Hot Module Replacement enabled.
2 main.js:20 [WDS] App updated. Recompiling...
main.js:20 [WDS] App hot update...
main.js:20 [HMR] Checking for updates on the server...
main.js:1 GET http://localhost:8080/68003e2dfaa592e9b4dc.hot-update.json 404 (Not Found)
main.js:20 [HMR] Cannot find update. Need to do a full reload!
main.js:20 [HMR] (Probably because of restarting the webpack-dev-server)
I didn't restart the dev server...
Here's my config:
const path = require("path")
const webpack = require("webpack")
var buildEntryPoint = function(entryPoint){
return [
entryPoint,
'webpack/hot/only-dev-server',
'webpack-dev-server/client?http://localhost:8080'
]
}
module.exports = {
entry: {
main: buildEntryPoint("./src/main.js"),
channel: buildEntryPoint("./src/channel.js")
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js"
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'react-hot-loader!babel-loader'
}]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
contentBase: path.join(__dirname),
hot: true,
inline: true,
port: 8080
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
I've tried searching in the different folders of my project to see if the file was there, but with no luck. Webpack is at version 2.7.0 and the dev server at 2.6.1.
Where's the issue here, why does it request a file that doesn't exist?

Debugging webpack/browserify React app in IntelliJ/WebStorm

I followed almost all guides I found online and I can not make debugger in IntelliJ stop at breakpoints.
I am developing React app with router. Backend is in Play Framework.
I tried generating source map using. This is from gulpFiles:
var bundler = watchify(browserify('./frontend/app.jsx', { debug: true }).transform(babel, {
presets: ["es2015","react","stage-3"],
plugins: [
"transform-decorators-legacy",
"transform-runtime"
]
}));
Source maps were generated; I was able to debug in Chrome debugger but I am not able in IntelliJ. I only see console output.
I tried generating with webpack:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public/javascripts');
var APP_DIR = path.resolve(__dirname, 'frontend');
var config = {
entry: APP_DIR + '/app.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader'
}
]
},
devtool: "source-map"
};
module.exports = config;
Same thing I can not stop at breakpoints in IntelliJ.
I configured JavaScript debug like this:
Name: React Debug
URL: http://localhost:9000/index
Remote URLs of local files (optional) : ./frontend
Still no luck and breakpoints are not working. What am I missing??
I managed to get it working with Webpack.
I was using npm task to run webpack and instead of :
webpack -d --watch
as was suggested everywhere. I used this:
webpack --debug --output-pathinfo --watch

Webpack - [HMR] Hot Module Replacement is disabled

I've looked around, but can't get any of the answers I've seen on stackoverflow to work.
I cannot use the command line for webpack or the webpack dev-server; I am restricted to using the Node API.
Below is how I am using webpack.
webpack.config.js
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
// i've also tried webpack/hot/dev-server here
'webpack/hot/only-dev-server',
path.join(__dirname, 'src', 'js', 'app.jsx')
],
output: {
path: path.join(__dirname, 'dist', 'js'),
filename: 'script.js',
publicPath: '/dist/'
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel']
}]
},
plugins: []
};
contained in a gulp task "start"
gulp.task('start', function (callback) {
var config = Object.create(require('webpack.config.js'));
config.plugins.push(new webpack.HotModuleReplacementPlugin());
var devServer = new webpackDevServer(webpack(config), {
stats: { colors: true },
contentBase: path.resolve(__dirname, 'dist'),
progress: true,
inline: true,
hot: true
});
});
What I expect
When I run gulp start, I expect the webpack dev server to spin up, allowing me to hit localhost:3000/. This should load an index.html from my project's /dist/ folder. So far so good. I expect that when I make a change to a file (e.g., app.jsx), that the change would be present.
What is actually happening
I am getting the error "[HMR] Hot Module Replacement is disabled", with no further explanation.
Any help would be appreciated. I have been trying to get hot reloading working for a full day.
in your webpack.config.js on the plugins section try this,
plugins: [new webpack.HotModuleReplacementPlugin()]
I know you are pushing the plugin in your gulp task but you have to use --hot --inline on cli or on your npm script
Try to run webpack as
webpack-dev-server --hot --inline in packge.json,
somehow official docs is wrong now.

Webpack-dev-server compiles files but does not refresh or make compiled javascript available to browser

I'm trying to use webpack-dev-server to compile files and start up a dev web server.
In my package.json I have the script property set to:
"scripts": {
"dev": "webpack-dev-server --hot --inline",
}
So the --hot and --inline should enable the webserver and the hot reloading (as I understand it).
In my webpack.config.js file I set the entry, output, and devServer settings as well as add a loader to look for changes in .vue files:
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/public',
publicPath: '/public',
filename: 'bundle.js'
},
devtool: 'source-map',
devServer:{
contentBase: __dirname + '/public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
So with this setup, I run npm run dev. The webpack-dev-server starts up, the module loader test works (i.e. when I save any .vue file it causes webpack to recompile), but:
The browser never refreshes
The compiled javascript that gets stored in memory is never made available to the browser
On that second bullet, I can see this because in the browser window the vue placeholders are never replaced and if I open up the javascript console the Vue instance is never created or made available globally.
What am I missing?
Two things were causing my problems here:
module.exports = {
entry: './src/index.js',
output: {
// For some reason, the `__dirname` was not evaluating and `/public` was
// trying to write files to a `public` folder at the root of my HD.
path: __dirname + '/public',
// Public path refers to the location from the _browser's_ perspective, so
// `/public' would be referring to `mydomain.com/public/` instead of just
// `mydomain.com`.
publicPath: '/public',
filename: 'bundle.js'
},
devtool: 'source-map',
devServer:{
// `contentBase` specifies what folder to server relative to the
// current directory. This technically isn't false since it's an absolute
// path, but the use of `__dirname` isn't necessary.
contentBase: __dirname + '/public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
Here's the fixed webpack.config.js:
var path = require('path');
module.exports = {
entry: [
'./src/PlaceMapper/index.js'
],
output:{
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/')
},
devtool: 'source-map',
devServer:{
contentBase: 'public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
After a long search I found the solution for my problem, in my case output path wasn't configured correctly.
This configuration solved my problem:
const path = require('path');
module.exports = {
"entry": ['./app/index.js'],
"output": {
path: path.join(__dirname, 'build'),
publicPath: "/build/",
"filename": "bundle.js"
}....
the right solution
Tell dev-server to watch the files served by the devServer.watchContentBase option.
It is disabled by default.
When enabled, file changes will trigger a full page reload.
Example:
module.exports = {
//...
devServer: {
// ...
watchContentBase: true
}
};
I also had a problem with my devserver which stopping working. Previously it had worked, then I added a ton of extras to get a production build. Then when I came back to devserver it didn't work any more.
Took lots of sleuthing - eventually starting with a prior commit in git, then reintroducing changes one-by-one until I figured it out.
Turns out it was a change I had made to package.json, specifically this line:
"browserslist": "> 1%, not dead",
This was useful to guide postcss, regarding the browsers to target.
But, it stops devserver working. Workaround is to add this to the dev webpack config:
target: 'web',
I found the solution here: https://github.com/webpack/webpack-dev-server/issues/2812
Hope that saves someone a few hours of trouble!
Somehow, for my case, removing "--hot" makes it work. So, I removed hot: true
webpack.dev.js
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
publicPath: '/js/',
contentBase: path.resolve(__dirname, 'docs'),
watchContentBase: true,
}
});
webpack.common.js
output: {
path: path.resolve(__dirname, 'docs/js'),
filename: '[name].min.js',
library: ['[name]']
},
I had the same problem and I find that in addition to all those points, we also have to put the index.html together with the output bundle.js in the same folder and set the contentBase to this folder, either the root or a subfolder.
This happened to me as well after running two different applications on the same webpack-dev-server port after one another. This happened even though the other project was shut down. When I changed to a port that had not been used it started working directly.
devServer: {
proxy: {
'*': {
target: 'http://localhost:1234'
}
},
port: 8080,
host: '0.0.0.0',
hot: true,
historyApiFallback: true,
},
If you use Chrome like me then just open Developer Tools and click on Clear site data. You can also see if this is the problem by running the site in incognito mode.
It can happen because of ExtractTextPlugin. Deactive the ExtractTextPlugin in development mode. Use it only for production build.
I experienced a similar situation where webpack-dev-server was serving my index.html file but not updating. After reading a few posts I realized that webpack-dev-server does not generate a new js file but instead injects one into index.html.
I added the html-webpack-plugin to my app and with the following configuration in my webpack.config.js file:
const HtmlWebpackPlugin = require('html-webpack-plugin')
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
I then commented out the script tag referencing my entry js file in index.html. I can now run webpack-dev-server without any additional flags and any changes to my files will display in the browser instantly.
What worked for me:
cache: false
https://webpack.js.org/configuration/cache/
My case was that I got so deep into experimenting with Webpack features, but totally forgot that I had set inject to be false the entire time like so...
new HTMLWebpackPlugin({
inject: false,
...
}),
Switching that on was my ticket.
I'll add my own special tale of Webpack --watch woe to the wall of suffering here.
I was running
webpack --watch
in order to build a Typescript project. The compiled .js files would update, but the bundle that the browser was seeing would not. So I was basically in the same position as the OP.
My problem came down to the watchOptions.ignored parameter. The original author of the build config had set up ignored as a filter function, which turns out to not be a valid value for that parameter. Replacing the filter function with an appropriate RegExp got the --watch build working again for me.
What helped me was introducing devServer.devMiddleware. For example, in webpack-dev-server 4.10.0, property contentBase was not available anymore.
devServer: {
devMiddleware: {
index: true,
publicPath: './build/static/',
serverSideRender: true,
writeToDisk: true,
}
},
Your project tree is not clear, however the problem may be in contentBase setting. Try to set contentBase: __dirname

Categories