Uncaught ReferenceError: process is not defined webpack - process

With:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin")
const path = require('path')
module.exports = [
new ForkTsCheckerWebpackPlugin(),
];
I get this error : Uncaught ReferenceError: process is not defined
Based on what I found :
Webpack 5 - Uncaught ReferenceError: process is not defined
Webpack 5+Process is not defined triggered by stream-browserify
https://webpack.js.org/plugins/provide-plugin/
I should add webpack.ProvidePlugin
But when I add ProvidePlugin to the webpack.config file:
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin")
const path = require('path')
const webpack = require('webpack')
module.exports = [
new ForkTsCheckerWebpackPlugin(),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
]
I get this error: Uncaught ReferenceError: require is not defined
webpack : 5
node: 16.15.1
O.S: Ubuntu 20.04 Desktop
How to solve the problem?

Related

transformIgnorePatterns is not working properly for jest for react-native preset

Got this error
/node_modules/#react-native/polyfills/error-guard.js:14
type ErrorHandler = (error: mixed, isFatal: boolean) => void;
^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-native/jest/setup.js:469:6)
However, I have already set
transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-(native|universal|navigation)-(.*)|#react-native-community/(.*)|#react-navigation/(.*)|bs-platform|(#[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
]
or
transformIgnorePatterns": [
"node_modules"
]
I have set babel properly like
module.exports = function (api) {
api.cache(true);
const presets = ['#babel/preset-env', '#babel/preset-react'];
const plugins = ['#babel/plugin-proposal-class-properties'];
return {
presets,
plugins,
};
};
and I have already tried clearing the cache.
Does anyone have any idea?
Add #react-native to your Jest configuration. Such as:
transformIgnorePatterns": [
"node_modules/(?!(jest-)?#react-native|react-(native|universal|navigation)-(.*)|#react-native-community/(.*)|#react-navigation/(.*)|bs-platform|(#[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
]

run vue3 ssr on cloudflare workers

I'm trying to run a vue ssr app on cloudflare workers.
I generated a new project using wrangler generate test
I installed vue using npm install vue#next and npm install #vue/server-renderer
I edited the index.js file like this:
const { createSSRApp } = require('vue')
const { renderToString } = require('#vue/server-renderer')
const app = createSSRApp({
data: () => ({ msg: 'hello' }),
template: `<div>{{ msg }}</div>`
})
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const html = await renderToString(app)
return new Response(html, {status: 200})
}
I then used wrangler dev to test it, but when I access the page I get this error:
ReferenceError: __VUE_PROD_DEVTOOLS__ is not defined
at Module.<anonymous> (worker.js:8:104768)
at n (worker.js:1:110)
at Object.<anonymous> (worker.js:8:104943)
at n (worker.js:1:110)
at worker.js:1:902
at worker.js:1:912
Any help or guidance is appreciated
I faced similar issue and was able to fix it by defining a global constant (VUE_PROD_DEVTOOLS = false) during compile time.
Here is how my webpack prod config looks like:
const webpack = require('webpack');
const { merge } = require("webpack-merge");
const webpackCommon = require("./webpack.common");
const prodConfig = {
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__VUE_PROD_DEVTOOLS__: JSON.stringify(false)
}),
]
};
module.exports = merge(webpackCommon, prodConfig);

How do you enable source maps in Webpack?

I want to enable source maps in my webpack.config.js. I'm adding onto some opensource and their webpack.config.js looks weird.
webpack.config.js
// Entry point webpack config that delegates to different environments depending on the --env passed in.
module.exports = function(env) {
process.env.NODE_ENV = env;
return require(`./webpack.${env}.js`);
};
Here is what it returns if env = development
/**
* Webpack configuration for development.
*
* Contains plugins and settings that make development a better experience.
*/
const webpack = require("webpack");
const merge = require("webpack-merge");
const fs = require("fs");
const { execSync } = require("child_process");
const path = require("path");
const argv = require("yargs").argv;
const commonConfig = require("./webpack.common.js");
const DashboardPlugin = require("webpack-dashboard/plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
if (!fs.existsSync(path.resolve(__dirname, "vendor", "vendor-manifest.json"))) {
// This _should_ exist, since we run the command for you when you run `npm run dev`
console.log(
"Vendor files not found. Running 'npm run build:dev-dll' for you..."
);
execSync("npm run build:dev-dll");
console.log("Done generating vendor files.");
}
const devConfig = {
mode: "development",
main: {
devtool: "source-map",
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify("development")
}),
new webpack.DllReferencePlugin({
context: ".",
manifest: require("./vendor/vendor-manifest.json")
}),
new ForkTsCheckerWebpackPlugin({
tslint: true,
async: false,
silent: true
})
]
}
};
// Only enable the dashboard plugin if --watch is specified
// The dashboard plugin annoyingly doesn't allow webpack to exit,
// so we only enable it with --watch, which doesn't exit anyways
if (argv.watch) {
devConfig.main.plugins.push(new DashboardPlugin());
}
module.exports = merge.multiple(commonConfig, devConfig);
I don't know if source map should be added to webpack.config.js or maybe just the development version and I don't know how to add it cause these config files look odd to me.
The line... "devtool": "source-map" is correct, but it appears to be at the wrong depth.
Should be:
const devConfig = {
mode: "development",
devtool: "source-map",
main: {
...
}
};

How can I share webpack.config snippets between projects?

I have several webpack configurations with very similar webpack.config files. I like to put webpack.config parts in a shared module that (I include the shared module with "npm link"), but that doesn't work as can't find dependencies, like "webpack" as it's the first dependency it encounters.
17 07 2017 14:49:32.694:ERROR [config]: Invalid config file!
Error: Cannot find module 'webpack'
at Function.Module._resolveFilename (module.js:470:15)
First webpack.config lines:
const webpack = require('webpack');
const path = require('path');
....
How can I instruct webpack to search for the included dependences in node_modules of the project that includes the webpack.config?
I tried to realise this by adding the following to the resolve webpack.config section, but that doesn't help:
modules: [path.resolve(__dirname, "node_modules"), "node_modules"]
I think it's not used by the webpack.config itself but by the JS code that is processed by webpack.config.
I solved it by passing in required root dir as argument to the common webpack config, and use that to change the __dirname variable that is used to find plugins and other stuff.
In code:
The webpack.config.js:
const path = require('path');
const loader = require('lodash/fp');
const common = require('bdh-common-js/etc/webpack/webpack.config.common');
module.exports = function (env) {
if (env === undefined) {
env = {};
}
env.rootdir = __dirname; // Add the root dir that can be used by the included webpack config.
const result = loader.compose(
function () {
return common(env)
}
// Any other "fragments" go here.
)();
// Customize the webpack config:
result.entry = {
entry: ['./src/entry.js', './src/js/utils.js'],
}
result.resolve.alias.Context = path.resolve(__dirname, 'src/js/context');
...... more stuff..
return result;
}
And the common webpack.config part that receives the argument:
module.exports = function (env) {
if (env !== undefined) {
if (env.rootdir !== undefined) {
__dirname = env.rootdir;
}
}
....
const node_modules = path.resolve(__dirname, 'node_modules');
const webpack = require(node_modules + '/webpack');
const CleanWebpackPlugin = require(node_modules + '/clean-webpack-plugin');
....
}

Using Babelify to compile React results in React Router being undefined

I'm using Gulp for my build system, with Browserify for compiling my JS. I had been using Reactify for JSX compilation, but thought I'd switch to Babelify to get some additional ES2015 features. No errors are thrown when compiling, but when I load my site in the browser I get the following error in my JS console:
Uncaught ReferenceError: Router is not defined
The line the error is referring to is:
var React = require('react');
in the main component file that is being loaded on the page.
The places where I am importing React Router are in my App.jsx file (which is the entrypoint for the application) and my routes.jsx file, where I define the routes:
App.jsx
var React = require('react'),
Router = require('react-router'),
routes = require('./routes.jsx');
Router.run(routes, function(Handler, state) {
var routeClasses = '';
for (var i = 1; i < state.routes.length; i++) {
routeClasses += state.routes[i].name + ' ';
}
React.render(<Handler classes={routeClasses.trim()} />, document.getElementById('root'));
});
routes.jsx
var React = require('react');
Router = require('react-router'),
Route = Router.Route,
DefaultRoute = Router.DefaultRoute,
App = require('./_layout/App.jsx'),
Editor = require('./editor/Editor.jsx');
module.exports = (
<Route name="app" path="/" handler={App}>
<DefaultRoute name="editor" handler={Editor} />
</Route>
);
Everything was working fine when using Reactify rather than Babelify. I'm using Gulp for my build process:
gulp.task('js', function() {
var browserify = require('browserify'),
watchify = require('watchify'),
minifyify = require('minifyify'),
babelify = require('babelify');
function bundle() {
b.bundle()
.on('error', function(error){
gutil.log(error);
})
.pipe(source('app.js'))
.pipe(gulp.dest(paths.client.js.build))
.pipe(gulpif(!isStartup, browserSync.stream()));
isStartup = false;
}
var map = isProd ? false : 'app.map.json';
var b = browserify({
cache: {},
packageCache: {},
entries: paths.client.js.dev,
debug: true,
plugin: [watchify]
})
.transform(babelify, {presets: ['es2015', 'react']})
.plugin('minifyify', {
map: map,
output: paths.client.js.build + 'app.map.json',
});
b.on('update', function(){
bundle();
});
b.on('log', gutil.log); // output build logs to terminal
bundle();
});
The working version, using Reactify, simply omits the .transform(babelify...) line and adds transform: reactify to the browserify() initialization code, i.e.
var b = browserify({
cache: {},
packageCache: {},
entries: paths.client.js.dev,
debug: true,
transform: reactify,
plugin: [watchify]
});
It's working with es2015 import X from Y syntax, e.g.
import React from 'react'