how to use react-monaco-editor together with worker-loader? - create-react-app

Describe the bug
react-monaco-editor cannot be used together with worker-loader.
To Reproduce
create a new typescript app with CRA, run a min react-monaco-editor demo. (everything is fine)
install worker loader and add config in config-overrides.js, and start app.
example repo to reproduce
ERROR in ./node_modules/monaco-editor/esm/vs/editor/editor.worker.js
Module build failed (from ./node_modules/worker-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'replace')
at getDefaultChunkFilename (/Users//Documents/test/my-project/node_modules/worker-loader/dist/utils.js:23:24)
at Object.pitch (/Users//Documents/test/my-project/node_modules/worker-loader/dist/index.js:61:108)
Child vs/editor/editor compiled with 1 error
assets by status 1.27 KiB [cached] 1 asset
./node_modules/monaco-editor/esm/vs/language/json/json.worker.js 39 bytes [not cacheable] [built] [1 error]
ERROR in ./node_modules/monaco-editor/esm/vs/language/json/json.worker.js
Module build failed (from ./node_modules/worker-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'replace')
at getDefaultChunkFilename (/Users//Documents/test/my-project/node_modules/worker-loader/dist/utils.js:23:24)
at Object.pitch (/Users//Documents/test/my-project/node_modules/worker-loader/dist/index.js:61:108)
Child vs/language/json/jsonWorker compiled with 1 error
details of my config-overrides.js
const webpack = require('webpack');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = function override(config, env) {
config.plugins.push(
new MonacoWebpackPlugin({
languages: ['json']
})
);
config.stats = {
children: true
}
config.module.rules.push(
{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: {
inline: 'fallback',
filename: '[contenthash].worker.js',
},
},
},
{
test: /\.worker\.ts$/,
use: [
{
loader: 'worker-loader',
options: {
inline: 'fallback',
filename: '[contenthash].worker.js',
},
},
'ts-loader',
],
},
);
return config;
};
Environment (please complete the following information):
OS: MacOS
Browser Chrome
Bundler webpack5 (CRA)
[ ] I will try to send a pull request to fix this issue.

I have solved it. It seems not to be a problem of react-monaco-editor or monaco-editor.
The problem is between worker-loader and monaco-editor-webpack-plugin.
I temporarily update my worker-loader config to match workers in my src folder only and solve this problem.
It could be better to figure out how to configure it in monaco-editor-webpack-plugin because it build files contains worker from monaco-editor without hashcode.

Related

How can I configure metro to resolve modules outside of my project directory?

For reasons that are out of my control, I need to resolve a module that is outside of my react-native project directory. So, consider the following directory structure:
react-native-project/
├─ App.jsx
├─ babel.config.js
external-directory/
├─ Foo.jsx
I would like any import Foo from 'Foo' inside of react-native-project to resolve ../external-directory/Foo.jsx. My first attempt at this was to use babel-plugin-module-loader with the following configuration:
plugins: [
[
'module-resolver',
{
alias: {
Foo: '/absolute/path/to/external-directory/Foo',
},
},
],
],
This doesn't work, with metro emitting the following error:
error: Error: Unable to resolve module /absolute/path/to/external-directory/Foo from /absolute/path/to/react-native-project/App.jsx:
None of these files exist:
* ../external-directory/Foo(.native|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
* ../external-directory/Foo/index(.native|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
This error message is wrong: ../external-directory/Foo.jsx does exist. I've verified this numerous times. I've also set up a standalone babel package to test an identical import scenario, and babel correctly resolves the external module.
The other approach I took was to add a custom resolveRequest function in my metro.config.js:
const defaultResolver = require('metro-resolver').resolve;
module.exports = {
...
resolver: {
resolveRequest: (context, moduleName, platform, realModuleName) => {
if (moduleName === 'Foo') {
return {
filePath: '/absolute/path/to/external-directory/Foo.jsx',
type: 'sourceFile',
};
} else {
return defaultResolver(
{
...context,
resolveRequest: null,
},
moduleName,
platform,
realModuleName,
);
}
},
},
};
This also doesn't work, emitting the following error message:
error: ReferenceError: SHA-1 for file /absolute/path/to/external-directory/Foo.jsx (/absolute/path/to/external-directory/Foo.jsx) is not computed.
Potential causes:
1) You have symlinks in your project - watchman does not follow symlinks.
2) Check `blockList` in your metro.config.js and make sure it isn't excluding the file path.
The potential causes do not apply in this scenario: There are no symlinks nor does the blockList contain the external directory (I explicitly configured blockList: null to verify).
Is there any way to accomplish what I'm trying to do? Or does metro (either by design or incidentally) prevent this?
You can use a metro bundler build in option - extraNodeModules and watchFolders.
const path = require('path');
module.exports = {
resolver: {
...,
extraNodeModules: {
app: path.resolve(__dirname + '/../app')
}
},
...,
watchFolders: [
path.resolve(__dirname + '/../app')
]
};

responsive-loader with nuxt.js

I want to integrate responsive-loader into my Nuxt.js project which runs in SPA mode. (Optional I want to add Vuetify Progressive Image support also).
It will be a static hosting with Netlify.
Versions:
"nuxt": "^2.3.4"
"responsive-loader": "^1.2.0"
"sharp": "^0.21.1"
I found some solutions how to do it (https://stackoverflow.com/a/51982357/8804871) but this is not working for me.
When I run npm run build
I get an error message: "TypeError: Cannot set property 'exclude' of undefined"
My build section looks the following:
build: {
transpile: [/^vuetify/],
plugins: [
new VuetifyLoaderPlugin()
],
extractCSS: true,
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient, isServer }) {
// Default block
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
]
}
// Default block end
// here I tell webpack not to include jpgs and pngs
// as base64 as an inline image
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
/*
** Configure responsive-loader
*/
config.module.rules.push({
test: /\.(jpe?g|png)$/i,
loader: "responsive-loader",
options: {
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
});
}
}
The error is probably found in this section:
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
Like said I get this error message: "TypeError: Cannot set property 'exclude' of undefined".
I run this project along with vuetify. I also would like to enable the Progressive image support together with responsive loader. Does anybody know how to setup both rules together?
https://github.com/vuetifyjs/vuetify-loader#progressive-images
The easiest way to integrate responsive-loader into a Nuxt.js project is to use this module: https://www.npmjs.com/package/nuxt-responsive-loader
Disclaimer: I created the module
The problem with your config that it relies on rule.loader property but rule can be defined in use or oneOf config sections as well.
Another one problem is that nuxt internal config has several rules with url-loader(for images, videos, fonts ...).
In your case the rule, you tried to find, has use section and url-loader is defined there, that's why your find function found nothing and threw this error:
{
"test": /\.(png|jpe?g|gif|svg|webp)$/,
"use": [{
"loader": "url-loader",
"options": {
"limit": 1000,
"name": "img/[hash:7].[ext]"
}
}]
}
About responsive-loader, you should remove extensions you want to process with responsive-loader from url-loader rule to avoid unexpected behavior and conflicts, here is extend function working example:
extend(config, ctx) {
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/';
// find by reg ex string to not rely on rule structure
let urlRule = config.module.rules.find(r => r.test.toString() === imgTest);
// you can use also "oneOf" section and define both loaders there.
// removed images from url-loader test
urlRule.test = /\.(svg|webp)$/;
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/,
loader: "responsive-loader",
options: {
// place generated images to the same place as url-loader
name: "img/[hash:7]-[width].[ext]",
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
})
}
Yes, it looks dirty, but I think it's only way for now to change some loader.
What about vuetify - I think both loaders will conflict with each other and probably the solution is to use single loader that will work with your images.
Hope it helps.
Update for Nuxt >= 2.4.0:
They modified the rules array please update the following line:
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/i';
Then the code should work normally again.

how to prevent mini-css-extract-plugin from creating a js entrypint

I am relatively new to express + webpack, so i am unclear wether this is intended or not, and if not, how to properly configure it. the question is around the additional asset & entry point created when using the mini-css-extract-plugin.
webpack config:
Extract = require('mini-css-extract-plugin');
path = require('path');
Write = require('write-file-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
demo_scripts: path.resolve('server', 'scripts', 'demo.js'),
demo_styles: path.resolve('server', 'styles', 'demo.css')
},
output: {
path: path.resolve('.tmp'),
filename: '[name].js'
},
plugins: [new Write(), new Extract()],
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
},
{
test: /\.css/,
use: [
{
loader: Extract.loader
},
{
loader: 'css-loader'
}
]
}
]
}
};
webpack output
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
demo_styles.css 36 bytes demo_styles [emitted] demo_styles
demo_styles.js 3.89 KiB demo_styles [emitted] demo_styles
Entrypoint demo_scripts = demo_scripts.js
Entrypoint demo_styles = demo_styles.css demo_styles.js
my question is, why is demo_styles.js being created? although the css is being extracted, it almost seems like webpack is still creating a bundled js with css, but when i view that file, the only line in it is
eval("// extracted by mini-css-extract-plugin\n\n//# sourceURL=webpack:///./server/styles/demo.css?");
can anyone help explain what is going on here?
UPDATE
if i remove the demo_styles entry point, and configure it via the plugin init, no css asset is built.
({
plugins: [
new Write(),
new Extract({
filename: 'demo_styles.css'
})
]
});
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
Entrypoint demo_scripts = demo_scripts.js
the repo for this is here (note the express branch) https://github.com/brewster1134/bumper/tree/express
There are two workarounds for your problem. For both of them, you need to change the entry point of the Webpack configuration file. I, personally, prefer the first option.
Option 1:
Change the entry to the following:
entry: {
demo: [
path.resolve('server', 'scripts', 'demo.js'),
path.resolve('server', 'styles', 'demo.css'),
]
}
This will generate the following outputs (based on the filename you provided for Extract class and output section:
demo.js
demo_styles.css
Option 2:
For this option, you need to remove the CSS file from the entry point and import it inside the JS file:
webpack.config.js
...
entry: path.resolve('server', 'scripts', 'demo.js'),
...
demo.js
import './../styles.demo.css'
//rest of your JS codes
This solution will generate the same output as Option1
Webpack pulls everything into a js file, then MiniCssExtractPlugin takes it out of that file, leaving a blank js file with // extracted by mini-css-extract-plugin.
My solution is to group your css and js in the entry section of webpack.config.js
entry: {
demo: {
import: [ path.join("server", "scripts", "demo.js"), path.join("server", "styles", "demo.css") ],
filename: "demo.js", // outputs demo.js, demo.css to your output directory
},
main: {
import: [ path.join("server", "scripts", "main.js"), path.join("server", "styles", "main.css") ],
filename: "main.js", // outputs main.js, main.css to your output directory
},
}
Also, so naming works well, use this for your plugins section:
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
],
Adjust the bundles "demo" and "main", as well as paths accordingly.
Please remove demo_styles from your entry point this is creating demo_styles.js.
instead you can inject css file like this:
plugins: [
new MiniCssExtractPlugin({
filename: 'demo_styles.css',
}),
Let me know if the issue still persists, Happy to help

Getting error while using "extract-text-webpack-plugin" with webpack : "Module build failed: Error: Parameter 'dependency' must be a Dependency"

Error while running webpack-dev-server
ERROR in ./css/app.scss
Module build failed: Error: Parameter 'dependency' must be a Dependency
at Compilation.process [as _addModuleChain] (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:347:9)
at Compilation.process [as addEntry] (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:423:7)
at SingleEntryPlugin.<anonymous> (/Users/roshankarki/Desktop/del_del/wp_tst/node_modules/webpack/lib/SingleEntryPlugin.js:22:15)
at Compiler.applyPluginsParallel (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:107:14)
at Compiler.compile (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compiler.js:394:7)
at Compiler.runAsChild (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compiler.js:203:7)
at Object.module.exports.pitch (/Users/roshankarki/Desktop/del_del/wp_tst/node_modules/extract-text-webpack-plugin/loader.js:81:18)
webpack: bundle is now VALID.
My webpack.config.js looks like this:
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
/* this defins path where entry files are to be found */
context: path.resolve('js'),
entry: ["./utils","./app"],
output: {
/* this is output directory of bundle.js */
path: path.resolve('build/'),
/* this is path of directory where bundle will be served in server */
publicPath: '/public/assets/',
filename: "bundle.js"
},
/* this plugin helps to generate seperate styles.css file rather in once single bundle.js file */
plugins: [
new ExtractTextPlugin("styles.css")
],
/* when server is loaded it tells where to look for index file accessed from root */
devServer: {
contentBase: 'public'
},
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "jshint-loader"
}
],
loaders: [
{
test: /\.es6$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
exclude: /node_modules/ ,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.scss$/,
exclude: /node_modules/ ,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
}
]
},
/* this will resolve file in common js style require without extension */
resolve: {
extensions: ['', '.js', '.es6']
},
watch: true
}
Before using this plugin everything was working fine. As i intend to output different bundle for css, i need to fix this issue.
Found issue in github but it did not help:
https://github.com/webpack/extract-text-webpack-plugin/issues/132
well updating node worked for me. I did this by running "brew update" and "brew upgrade" command, as i am using homebrew as a package manage in mac.
Following instruction in the git link provide in my question resulted in error as i was installing webpack and webpack-dev-server globally. I removed it and only had local copy which did the trick at the end.
command to list global copy of node modules installed:
npm list -g --depth=0
I use this command to remove global copy:
npm uninstall -g {replace_with_package_name}
command to check local copy:
npm list --depth=0

Cannot run unit tests on modules with dependencies on dojo 1.x using the Intern

We are just starting out with getting some unit tests running in the Intern on our dojo-based project.
What happens is that when the intern tries to load the module under test's dependencies we get the following error:
/<path/to/dev/folder>/app/node_modules/intern/node_modules/dojo/dojo.js:406
match = mid.match(/^(.+?)\!(.*)$/);
^
TypeError: Cannot read property 'match' of null at getModule (/<path/to/dev/folder>/app/node_modules/intern/node_modules/dojo/dojo.js:406:15) at mix.amd.vendor (/<path/to/dev/folder>/app/node_modules/intern/node_modules/dojo/dojo.js:832:17) at /<path/to/dev/folder>/app/src/simplebuilding/model/ModelError.js:10:1
at exports.runInThisContext (vm.js:74:17)
at Object.vm.runInThisContext (/<path/to/dev/folder>/app/node_modules/intern/node_modules/istanbul/lib/hook.js:163:16)
at /<path/to/dev/folder>/app/node_modules/intern/node_modules/dojo/dojo.js:762:8
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)
Here is my config file - I started by copying the example one, and adding the map section to the loader.
define({
proxyPort: 9000,
proxyUrl: 'http://localhost:9000/',
capabilities: {
'selenium-version': '2.41.0'
},
{ browserName: 'chrome', version: '40', platform: [ 'OS X' ] }
],
maxConcurrency: 3,
tunnel: 'NullTunnel',
loader: {
// Packages that should be registered with the loader in each testing environment
packages: [
{ name: 'dojo', location: 'src/dojo' },
{ name: 'dojox', location: 'src/dojox' },
{ name: 'dijit', location: 'src/dijit' },
{ name: 'app', location: 'src/app' },
{ name: 'tests', location: 'tests' }
],
map: {
'*': {
'dojo' : 'dojo'
},
app : {
'dojo' : 'dojo'
},
intern : {
'dojo' : 'node_modules/intern/node_modules/dojo'
},
'tests' : {
'dojo' : 'dojo'
}
}
},
suites: [ 'tests/model/modelerror' ],
functionalSuites: [ /* 'myPackage/tests/functional' */ ],
excludeInstrumentation: /^(?:tests|test\-explore|node_modules)\//
});
The file under test has dependencies on dojo/_base/declare, dojo/_base/lang, and dojo/Stateful, and that is about it.
I created a dummy class to test where there were no dojo dependencies and it runs fine.
I've tried switching the loader to be the local dojo 1.10.3 version we have in our project, and that throws entirely different errors about not being able to find the intern (even if I give it a package definition in the config). Those errors look like this:
{ [Error: ENOENT, no such file or directory '/<path/to/dev/folder>/app/node_modules/.bin/main.js']
errno: -2,
code: 'ENOENT',
path: '/<path/to/dev/folder>/app/node_modules/.bin/main.js',
syscall: 'open' }
Our project structure is pretty straight-forward:
root
|--src
|--dojo (dijit/dojox/dgrid/etc)
|--app
|--tests
|--intern.js (config file)
I've tried several variations besides changing the loader, like trying to make sure the base-path is correct. I've tried running it in Node 0.10.36, and 0.12.2. But every time I debug this with node-inspector when it gets to load the module for my file under test and the mid is null, and jumping back up the stack trace it looks fine, but something is lost in the vm.runInThisContext() call, and the mid disappears by the time getModule() is called.
Any help is appreciated - Thanks!
So I figured this out - we had modules we were loading inside of our project that used an old style of the define() function. We had moved from the old define('my.module.namespace', ['deps'], function(deps){ ... }); to replacing the dot namespace for the module in the first argument with null. We were doing this as a transitionary phase to removing that argument completely, but hadn't ever finished that transition. This was causing the dojo2 loader to think the "id" of the module was null, and that was causing the loader to not find a Module ID.
This was a completely silly mistake on our part, and this will help us modernize to the updated signature for future-dojo-readiness.