Browserify: override package and use different main file - javascript

Browserify's "browser" field in the package.json seems overloaded and I can't figure out a way to get around this issue
How would I shim several packages not necessary in the browser (such as ws and canvas) while also changing the "main" file for browserify's use
I was hoping something like this would work
{
"browser": {
"ws": "./src/browser/ws-shim",
"main": "./src/BrowserVersion"
}
}
src/browser/ws-shim
module.exports = global.WebSocket;
Repository in question has some specific Node functionality such as services over TCP and stream support which won't make sense in the browser. Meanwhile, we use node ports of several browser APIs to share code between the Node and Browserifyied versions of the lib

Use the browser key to map to your main file.
{
"browser": "./src/browserIndex.js"
}
Then use the aliasify transform to map the rest of your dependencies.
{
"browserify": {
"transform": [ "aliasify" ]
},
"aliasify": {
"aliases": {
"ws": "./src/browser/ws-shim"
}
},
"devDependencies": {
"aliasify": "^1.4.0"
}
}

Related

how can I use top level "await" in typescript next.js

When I use "await" on top-level like this:
const LuckyDrawInstance=await new web3.eth.Contract(abi)
I got a warning on the terminal: "set experiments.topLevelAwait true". When I tried to add this to "tsconfig.json", it still does not work. it says "experiments" property does not exist.
I could wrap it inside an async function but I want to set it without a wrapped function.
It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await.
module.exports = {
webpack: (config) => {
// this will override the experiments
config.experiments = { ...config.experiments, topLevelAwait: true };
// this will just update topLevelAwait property of config.experiments
// config.experiments.topLevelAwait = true
return config;
},
};
NOTE
You have to use it outside the functional component:
export default function Navbar() {
// this will throw error
// Syntax error: Unexpected reserved word 'await'.
const provider=await customFunction()
return (
<section>
</section>
);
}
Warning
Since it is experimental, it might be broken in some versions
The latest solution as of writing this post that worked for me is using Babel instead of SWC since Next.js does not allow custom SWC configuration, therefore, you cannot allow topLevelAwait through .swcrc file.
Add Babel plugin called #babel/plugin-syntax-top-level-await into your package.json.
eg.
{
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
Create .babelrc file in the root directory of your project where package.json lives.
Inside .babelrc make sure to include next/babel preset and the topLevelAwait plugin.
eg.
{
"presets": ["next/babel"],
"plugins": [
"#babel/plugin-syntax-top-level-await"
]
}
This is the easiest solution until Next.js team allows us to include SWC configuration. Note that by doing this you will not have SWC performance benefit since it will be disabled in favor of Babel.
I have been struggling with this for 2-3 days. Here is a solution that works. Please follow the following steps.
1. Copy paste the following in your package.json
{
"name": "projectname",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"dev": "next dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"#truffle/hdwallet-provider": "^2.0.1",
"fs-extra": "^10.0.0",
"ganache-cli": "^6.12.2",
"mocha": "^9.1.4",
"next": "^12.0.8",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"solc": "^0.8.9",
"web3": "^1.7.0",
"#babel/plugin-syntax-top-level-await": "^7.14.5"
},
"devDependencies": {
"#babel/plugin-syntax-top-level-await": "^7.14.5"
}
}
2. Delete your node_modules folder
3. Goto your project's root directory and reinstall all the packages using npm install command
4. Create a new file in your project's root directory and call it "next.config.js"
5. Copy paste following code in next.config.js file and save.
module.exports = {
// target: 'experimental-serverless-trace',
webpack: (config) => {
config.experiments = config.experiments || {};
config.experiments.topLevelAwait = true;
return config;
},
};

How to create typescript library with webworkers using worker-loader

I try to create typescript library with web workers. When I test my code with webpack-dev-server everything looks good, all files are found, but when I make npm run build and try to use lib in another local project (npm install /local/path), I see GET http://localhost:8080/X.worker.js in browser console.
webpack.config.js:
const path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: {
'mylib': './src/index.ts',
'mylib.min': './src/index.ts',
},
output: {
path: path.resolve(__dirname, '_bundles'),
filename: '[name].js',
libraryTarget: 'umd',
library: 'mylib',
umdNamedDefine: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
optimization: {
minimize: true
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader',
exclude: /node_modules/,
query: {
declaration: false,
}
},
{
test: /\.worker\.js$/,
use: {
loader: "worker-loader"
}
},
]
}
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"lib": [
"webworker",
"es2015",
"dom"
],
"moduleResolution": "node",
"sourceMap": true,
"strict": true,
"alwaysStrict": true,
"outDir": "lib",
"resolveJsonModule": true,
"declaration": true,
"skipLibCheck": true,
"allowJs": true
},
"include": [
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules",
"lib",
]
}
package.json
{
"name": "mylib",
"version": "1.0.0",
"description": "",
"main": "_bundles/mylib.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack",
"build": "rm -rf ./lib && tsc",
"serve": "webpack-dev-server",
"clean": "rm -rf _bundles lib lib-esm",
"newbuild": "npm run clean && tsc && tsc -m es6 --outDir lib-esm && webpack"
},
"repository": {
"type": "git",
"url": "..."
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "..."
},
"homepage": "...e",
"devDependencies": {
"prettier": "^2.1.2",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0",
"worker-loader": "^3.0.5"
},
"dependencies": {
...
}
}
Example on how I import workers:
import X from "worker-loader!./X";
I found myself in the exact same situation a few months back. I found a solution that worked for me, but first lets discuss why this is happening.
The problem:
There are 3 layers here.
The development layer of your library
The build layer of your library
The application that consumes the build of your library
Layer 1 is simple. In whatever file you want to create a new worker, say its index.ts, you do your import X from "worker-loader!./X". Your index.ts knows exactly where to find your worker file. That's why things work on your webpack-dev-server.
Layer 2 is where things get weird. When you process the worker file with worker-loader, webpack outputs several files. Your config says filename: '[name].js', which would output a file for every file in your source folder, all on the same level in your _bundles folder. Webpack sees your import X from "worker-loader!./X", and it also sees your target name and location for the imported file, and the file doing the importing. It rewrites the location of the web worker file within the index.js output bundle to an absolute path relative to the rest of the bundle. You can control this more carefully by using the publicPath option in the worker-loader. But this doesn't really solve the issue, as you are only setting the publicPath as an absolute path, which leads us to step 3...
Layer 3, where you try to consume your package, is where things go wrong. You could never anticipate where one might try to import { makeAWorker } from 'your-library' in their code. Regardless of where they import it, the build file (in the consumer app's node_modules) will be using the path that webpack wrote into the build of index.js to look for the worker file, but now the absolute path is relative to your consumer project (usually the home path, like where index.html lives), not to the node_modules folder of the build. So your consumer app has no idea where to find the worker file.
My solution: a bit of a hack
In my scenario, I decided that the content of my worker files was simple enough to create a worker from a string, and import it that way. For example, a worker file looked like this:
// worker.ts
// Build a worker from an anonymous function body
export default URL.createObjectURL(
new Blob([
'(',
function () {
// actual worker content here
}.toString(),
')()', ],
{ type: 'application/javascript' }
)
);
Then in the place where I want to spawn the worker:
// index.ts
import workerScript from './worker';
const myWorker = new Worker(workerScript, {worker_options});
This works because now you are no longer asking webpack to create a file and write the correct import locations for you. In the end, you won't even have separate files in your bundle for your worker scripts. You can ditch worker-loader altogether. Your index.ts will create the Blob and its URL, and your consumer application will find the worker script at that URL which is dynamically generated at runtime.
A hack indeed
This method comes with some serious drawbacks, which led me to ask the question bundle web workers as integral part of npm package with single file webpack output. The issue is that inside your worker script, you really don't have the option to import anything. I was lucky in that my worker was relatively simple. It depended on a single node_module, which itself had no dependencies. I started out by simply including the source of that module in the script, but as I had multiple scripts that needed that same external module, I ended up passing it as a piece of data to the worker when it gets spawned:
import { Rainbow } from './utils';
var data = {
id,
data
RainbowAsString: Rainbow.toString(),
};
myWorker.postMessage(data);
Then within the worker I simply convert RainbowAsString back to a function and use it. If you are curious to see more detail, you can check out the library I built with this method: leaflet-topography. Look into the src/TopoLayer.ts file to see how the workers are used, and the src//workers folder to see how I set up the worker blobs.
Conclusion
I think there must be a better way. One possible quick fix would be to write a copy script that would copy the worker files from node_modules/yourLibrary to the build folder of your consumer app. But this doesn't make for great portability, and other peple are going to have to do the same thing to get your library working with their app. My solution isn't perfect, but it works for simple-ish worker scripts. I am still thinking about a more robust solution that allows workers to do their own imports.
Edit: A proper solution:
So after writing this answer, I was inspired to join the conversation How can I use this to bundle a library? in the webpack-loader repo. Apparently, when webpack 5 was released about 2 months ago, they added support for this syntax:
new Worker(new URL('./path/to/worker.js', import.meta.url))
I have not tried this, but it looks like the solution you need (and the solution I needed 2 months ago when I was coming up with my hack). Try this out - it may be exactly what you need to tell webpack to bundle your library while stil maintaining the relationship between worker script and the script that imports it.

Module not found: Error: Can't resolve 'crypto'

I am getting the following list of errors when I run ng serve.
My package JSON is as follows:
{ "name": "ProName", "version": "0.0.0", "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e" }, "private": true, "dependencies": {
"#angular-devkit/build-angular": "~0.12.0",
"#angular/animations": "5.2.10",
"#angular/common": "5.2.10",
"#angular/compiler": "5.2.10",
"#angular/compiler-cli": "5.2.10",
"#angular/core": "5.2.10",
"#angular/forms": "5.2.10",
"#angular/platform-browser": "5.2.10",
"#angular/platform-browser-dynamic": "5.2.10",
"#angular/router": "5.2.10",
"#types/dotenv": "^4.0.3",
"#types/errorhandler": "0.0.32",
"#types/express": "^4.16.0",
"#types/node": "^10.5.1",
"apostille-library": "^7.1.0",
"core-js": "^2.5.4",
"dotenv": "^6.0.0",
"errorhandler": "^1.5.0",
"express": "^4.16.0",
"nem2-sdk": "^0.9.7",
"rxjs": "~6.3.3",
"stream": "0.0.2",
"tslib": "^1.9.0",
"typescript": "^2.9.2",
"zone.js": "~0.8.26" } }
The error I get :
ERROR in ./node_modules/aws-sign2/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/aws-sign2' ERROR in
./node_modules/aws4/aws4.js Module not found: Error: Can't resolve
'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws4'
ERROR in ./node_modules/ecc-jsbn/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/ecc-jsbn' ERROR in
./node_modules/http-signature/lib/verify.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/http-signature/lib/signer.js Module not found:
Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/nem-sdk/build/external/nacl-fast.js Module not
found: Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/nem-sdk/build/external'
ERROR in ./node_modules/nem-sdk/node_modules/aws-sign2/index.js
I ran into a similar issue lately while trying to use another library (tiff.js) in a small project I was experimenting with.
The way I got around this was to add the following to my package.json file, right after the devDependencies section.
"devDependencies": {
...
},
"browser": {
"crypto": false
}
This didn't seem to have any adverse effect when trying to use the library in the application.
Adding this setting in tsconfig.json file under that project resolve this warning
"compilerOptions": {
"baseUrl": "./",
"paths": {
"crypto": [
"node_modules/crypto-js"
]
}
I like R. Richards's answer, but I thought it would be useful to provide some more information.
This is a known issue with Angular, and the Angular CLI dev team seems to think it's a feature rather than a bug. I, as well as other developers in this issue thread, disagree. Contributors to that thread provided several workaround fixes, but my project didn't compile successfully until I implemented R. Richards' solution. I didn't revert the previous changes, though, so tacnoman's and GrandSchtroumpf's fixes may be of use to others.
Some, like clovis1122 here and others in that issue thread, have questioned why a web app would need access to these libraries and why the necessary tasks can't be completed on the server side instead. I can't speak for everyone, but my use case is that, when authenticating a user account, Strapi responds with a JSON Web Token string that must be decoded by the client. Since the necessary library depends on crypto and stream, you won't be able to extract the JWT expiration time unless those dependencies are available.
In case anyone has trouble extrapolating from R. Richards' answer, you'll have to set to false any dependencies that are showing up in "can't resolve x" errors. For example, the critical part of my package.json is:
"browser": {
"crypto": false,
"stream": false
}
I thought I would expand on what Tarique Ahmed wrote in his answer.
I was using an npm module that had the following line in the code:
const crypto = require('crypto');
I couldn't add:
"browser": {
"crypto": false
}
to the package.json because the crypto package had to be part of the build.
It turns out that during the compilation process Angular seems to have decided to install the crypto-browserify package instead of crypto.
Adding the following to the tsconfig.json file instructs the build to use the crypto-browserify library every time that crypto is required. As you can see, I had the same issue for the stream package.
"paths": {
"crypto": [
"node_modules/crypto-browserify"
],
"stream": [
"node_modules/stream-browserify"
]
}
After having the same issue with Angular 11 and crypto-js 4 (and manually setting the path in tsconfig.json), I found rolling back crypto-js to version 3.1.9-1 fixed the issue. It seems a change made in version 4 caused the issue.
npm install crypto-js#3.1.9-1
Explained here in repo issues:
GitHub issue
If you upgraded to Webpack 5, you need to add this to your webpack config file:
resolve: {
fallback: { crypto: false },
},
aws-sign2 is a NodeJS package (and crypto is a NodeJS module), but it looks like you're dealing with a web application. It makes sense that the crypto module is not available in that environment.
Would it be possible to complete what you need to do server-side? Otherwise, you may need to look for another package.
For Laravel Inertia JS project, my solution was:
1- Add dependencies to package.json
"dependencies": {
"crypto-browserify": "3.12.0",
"crypto-random-string": "^3.3.0",
"stream": "^0.0.2"
}
2-In webpack.config.js:
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
},
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream'),
},
},
};
3-Install, build and run:
npm install && npm run watch
I have resolved my issue using below steps:
Add below to tsconfig.json to resolve crypto warning:
"paths": {
"crypto": [
"node_modules/crypto-js"
]
},
and add below to angular.json
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
],
...
}
My Error
In my Case the import { get } from "express/lib/response" is the culprit, which is automatically added by vs-code.
So, after removing it I solved my issue
When using #Laravel framework with Laravel Mix this is going to be more trick. I spend some hours on this NPM nightmare and found a solid solution.
So, in your webpack.mix.js you find the 'comment'
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
Now just below that comment add the following lines;
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.LoaderOptionsPlugin({
exports: {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
}
}
}
})
]
};
});
Now you can use Laravel Mix just like you would edit webpack.config.js ;)
Also; In package.json remove:
--no-progress --hide-modules
These are no longer valid for WebPack >= 5. Enjoy!
After a deep a research i found that the solution is very simple: replace
import * as CryptoJS from 'crypto-js'; with declare var CryptoJS;
Using direct import may not work with ES6 Enviornment..
This may help you.
$ npm i crypto-js#latest // For using latest version 4
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { secretKey } from './environments/environment';
/** Encryption */
const data = {key: 'Test Value'};
const ciphertext = AES.encrypt(JSON.stringify(data), secretKey).toString();
console.log('Encrypted Data', ciphertext);
/** Decryption */
const bytes = AES.decrypt(ciphertext, secretKey);
const decryptedData = JSON.parse(bytes.toString(Utf8));
console.log('Decrypted Data', decryptedData);
https://github.com/brix/crypto-js/issues/168#issuecomment-785617218
Add the option allowedCommonJsDependencies with literal "crypto-js" in a array, this in file angular.json:
"architect":
"build": {
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
]
},
}
}
This will disable all warnings, tested in Angular 11.
My problem was that I was trying to build to node and web using the same code, but is not possible to built to web while importing a WebSocket dependency, ws in my case
So the solution is by using a wrapper:
Install a wrapper, I will use isomorphic-ws because is made for ws
npm i --save isomorphic-ws
Remove const WebSocket = require('ws')
Replace with:
const WebSocket = require('isomorphic-ws')
I ended up going into
node_modules/react-scripts/config/webpack.config.js
and adding:
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
https: require.resolve("https-browserify"),
http: require.resolve("stream-http"),
url : require.resolve("url")
}
And now my react app builds with errors but no dependency issues. Ill update this when I get it building.
Add
npm install crypto-js
Or Add a specific version according to your project need
npm install crypto-js#4.0.0
Also, run the above commands in Window "run as administrator" or in Linux use sudo
Alot of answers already but still none of them works. In my case I see warning message
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }
comment from #stewii did helped me to resolved this.
There is now an ES modules version called "crypto-es". It clears these warnings. npmjs.com/package/crypto-es
After this I imported cryptoES
import CryptoES from 'crypto-es';
and remove the existing import of cryptoJs. Re-start the compile and Voila.. The warning message is gone.
I tried a lot of the solutions above but the final thing that worked for me was downloading the crypto-es package and adding, "type":"module" to package.json.
https://www.npmjs.com/package/crypto-es
I was facing same issue, Just run node patch.js and it worked. The issue is, browser doesn't allow server files to be run on browser. In case you need some of these, You can use node patch.js. If you don't want to run any server file on browser, you can simply apply above mentioned solution by #R.Richards. Might be helpful for someone..
In my case, the solution described by R.Richards doesn't work.
However, following several threads along this issue, I finally understood where to insert the recommendation provided in the warning message and solved this warning.
WARNING in ./node_modules/bcryptjs/dist/bcrypt.js 64:13-45
Module not found: Error: Can't resolve 'crypto' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\bcryptjs\dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
**If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }**
Differently from many contributors, I didn't want to install crypto-browserify as I don't need it (*), and I chose to add the fallback { "crypto": false }.
However I didn't know where to add this fallback. After reading several threads, I found it was in the webpack.config.js file, which is located in the directory node_modules/react_scripts/config.
Adding this fallback made the compilation succeed without any warning.
(*) PS : I once tried to add the following fallback { "crypto": require.resolve("crypto-browserify") }, but it led to generation of 7 errors, requiring other modules :
Failed to compile.
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/cipher-base/index.js 2:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/readable-stream/lib/_stream_readable.js 43:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/_stream_writable.js 65:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/internal/streams/buffer_list.js 63:15-32
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib\internal\streams'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/ripemd160/index.js 3:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\ripemd160'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safer-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
webpack compiled with 7 errors
I had this problem in ReactJS with create-react-app(facebook)
Solution:
First install the necessary packages "crypto-browserify"
Modify webpack.config.js in reactjs with create-react-app this file is inside:
node_modules/react-scripts/config/webpack.config.js
Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
}
}
}
}
Note: Is possible you need other packages how "stream-browserify" the steps are same. This solution works, but when the webpack project starts it shows warnings
Pd: I am not native speaker English, but I hope understand me.

How to load external librarie i.e. moment.js in Amber-Smalltalk?

I don't get moment.js or other external libraries like tinymce working in my amber application.
These are the steps I did so far:
run bower install moment --save
added a moment.and.json in my applications root directory containing the correct path in bower_components:
{"paths": {"moment": "moment"}}
added "moment" to deploy.js
run grunt devel
My first problem is that from inside the js console momentjs seems to be not loaded, even if the file shows up in network traffic.
After that how do I use moment.js from inside Amber?
How do I need to wrap it?
I read how-to-add-a-non-amber-library-with-bower-for-example-processing and all the other explanations but still have problems grabbing the exact process.
All the documentation I read was inconclusive to me. Isn't there a simple explanation on how to do it?
The amd file has to look like this:
{
"paths": {
"moment": "moment"
},
"shim": {
"moment": {
"exports": "moment"
}
},
"config": {
"moment": {
"noGlobal": false
}
}
}
As it seems it has to be required like this to work properly: window.moment = require('moment');

How do I get JUnit XML output from Jest?

I have a React app that has Jest tests. I'm configuring Jest in my package.json:
…
"jest": {
"setupEnvScriptFile": "./test/jestenv.js",
"setupTestFrameworkScriptFile": "./test/setup-jasmine-env.js",
"testRunner": "node_modules/jest-cli/src/testRunners/jasmine/jasmine2.js",
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react"
]
},
…
The setup-jasmine-env.js looks like this:
var jasmineReporters = require('jasmine-reporters');
jasmine.VERBOSE = true;
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: "output/",
filePrefix: "test-results"
})
);
It took a bit of working to get that jasmine env setup correctly, but I"m not seeing anything in the output directory (indeed, it isn't created and creating it myself doesn't help). I suspect that my alterations to the jasmine var aren't the same one that Jest is using, but I can't figure out how to hook them together.
If you use a more recent version of jest (I'm looking at 16.0.2), you don't need to specify the testrunner because jasmine is the default. You also don't need the unmockedModulePathPatterns section of the jest config.
I.e. you just need to include the following devDependencies in your package.json:
"jasmine-reporters": "^2.2.0",
"jest": "^16.0.2",
"jest-cli": "^16.0.2"
And add this jest config to your package.json (note: you no longer need the unmockedModulePathPatterns section):
"jest": {
"setupTestFrameworkScriptFile": "./setup-jasmine-env.js"
}
And then use Drew's setup-jasmine-env.js from the question.
Jest has support for its own reporters via the testResultsProcessor config. So I wrote up a little thing that generates compatible junit xml for this. You can find it here. https://github.com/palmerj3/jest-junit
looks like all you're missing from the above setup is to add jasmine-reporters to unmockedModulePathPatterns, so give the following a go:
"jest": {
...
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react",
"./node_modules/jasmine-reporters"
]
},
Hope that helps!
UPDATE: for anyone else experiencing this problem, I have put a working demo up here.

Categories