Uncaught TypeError: $ is not a function in core-js - node.js

I'm trying to install the BigCommerce Open Checkout script, and I'm currently getting this error when I try to run the basic installation locally:
Uncaught TypeError: $ is not a function
at eval (es.array.index-of.js?c975:15)
at Object../node_modules/core-js/modules/es.array.index-of.js
That file is:
'use strict';
var $ = require('../internals/export');
var $indexOf = require('../internals/array-includes').indexOf;
var arrayMethodIsStrict = require('../internals/array-method-is-strict');
var arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');
var nativeIndexOf = [].indexOf;
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
var STRICT_METHOD = arrayMethodIsStrict('indexOf');
var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
$({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? nativeIndexOf.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
}
});
So far, I've tried updating core-js and NPM repeatedly with no luck.

core-js should not be compiled by Babel. When using webpack + babel to compile your code, you need to ensure that the webpack module rule for babel-loader excludes core-js.
Option 1
Tell webpack to not use babel-loader for any of the dependencies in your node_modules. Since core-js is a dependency in node_modules, this excludes core-js from being processed by babel.
// webpack.config.js
// This code snippet shows only the relevant part of the webpack config
module.exports = {
module: {
rules: [
{
test: /\.m?(j|t)sx?$/,
// Excluding node_modules means that core-js will not be compiled
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
}
Option 2
Tell webpack to compile all dependencies with babel, except for the core-js dependency:
// webpack.config.js
// This code snippet shows only the relevant part of the webpack config
module.exports = {
module: {
rules: [
{
test: /\.m?(j|t)sx?$/,
// Compile all node_modules except core-js
include: {
and: [/node_modules/],
not: [/core-js/]
},
use: ['babel-loader']
}
]
}
}
Relevant Links
https://github.com/zloirock/core-js/issues/912
https://webpack.js.org/configuration/module/#ruleexclude
https://webpack.js.org/configuration/module/#ruleinclude
https://webpack.js.org/configuration/module/#rule-conditions

Related

Package.json exports with webpack 5 - dynamically imported module not found

I am having a bit of trouble reconciling the path of a dynamic import for i18n locales. Here's the relevant code -
function getLoader(
lang: SupportedLanguage,
ns: SupportedNamespace
): NamespaceLoader | undefined {
const matrixToCheck = UNSUPPORTED_MATRIX[ns];
const isSupported = matrixToCheck && matrixToCheck.indexOf(lang) === -1;
if (isSupported) {
const path = `./locales/${lang}/${ns}.json`;
const name = `${lang}_${ns}`;
const named = {
[name]: () => import(`${path}`),
};
return named[name];
}
}
...
// eventual output
const SUPPORTED_LANGUAGES = {en: {namespace1: () => import('./locales/en/namespace1.json')}
My goal is manage all of the relevant translations in a single npm package, handle all of the dynamic import set-up at build time, and then consumers can invoke the getter (getTranslation in this case) in their respectives apps for the language and namespace of their choice to get the payload at runtime.
Based on this GH thread, I wanted to reconcile the locale dist path via the package.json
...
"exports": {
".": "./dist/src/main.js",
"./": "./dist/"
},
...
e.g. when I publish the package, based on that exports config, the consumer would know know how to reconcile the path, either relative or package-name-prefix when the getter is invoked
const fn = () => import('./locales/fr/myNamespace.json') /// doesn't work
const anotherFn = () => import('#examplePackageName/locales/fr/myNamespace.json') /// doesn't work
Since everything is dynamic, I am using the CopyWebpackPlugin to include the locales in the dist folder.
This works as expected locally, but when I create the dist, I get the error Error: Module not found ./relative/path/to/the/json/I/want.json.
My question:
What am I missing? Is there a simple way to expose these translations so that other apps can include them in their bundles via an npm-installed package?
Here's my Webpack config, happy to provide other info as needed
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const getPlugins = () => {
return [
new CleanWebpackPlugin(),
new CopyPlugin({
patterns: [{ from: "locales", to: "locales" }],
}),
];
};
module.exports = {
mode: "production",
entry: {
main: "./src/main.ts",
},
output: {
path: path.join(__dirname, "dist"),
filename: "src/[name].js",
chunkFilename: "chunk.[name].js",
libraryTarget: "commonjs2",
},
resolve: {
extensions: [".json", ".ts", ".js"],
alias: {
"#locales": path.resolve(__dirname, "locales/*"),
},
},
plugins: getPlugins(),
module: {
rules: [
{
test: /\.ts$/,
exclude: [/\.test\.ts$/],
include: path.join(__dirname, "src"),
loader: "ts-loader",
},
],
},
};
Exports directive prescribes to define all files allowed for import explicitly (documentation). It allows developer to hide internal package file structure. What's not exported by this directive is only available to import inside the package and not outside of it. It's made to simplify maintenance. It allows developers to rename files or change file structure without fear of breaking dependent packages and applications.
So if you want to make internal files visible for import, you should export them with exports directive explicitly, like this:
{
"exports": {
".": "./dist/esm/src/main.js",
"./dist/shared/locale/fr_fr.json": "./dist/shared/locale/fr_fr.json"
}
}
I'm not sure wether Webpack handling this case, because it's an experimental feature yet. But this is how Node.js works now.
Why it is so
Changing your app file structure is a major change in semver terms, so you need to bump a version everytime you rename or delete files. To avoid it you can specify which files are part of public interface of the package.

setup webpack config in nextJS (next.config.js)

I'm working with NextJS and using react-data-export plugin to generate xls files.
in the description it says :
This library uses file-saver and xlsx and using
json-loader will do the magic for you.
///webpack.config.js
vendor: [
.....
'xlsx',
'file-saver'
],
.....
node: {fs: 'empty'},
externals: [
{'./cptable': 'var cptable'},
{'./jszip': 'jszip'}
]
but I have no idea how to implement it and got error like this :
The static directory has been deprecated in favor of the public directory. https://err.sh/vercel/next.js/static-dir-deprecated
Defining routes from exportPathMap
event - compiled successfully
> Ready on http://localhost:80 or http://localhost
> Ready on https://localhost:443 or https://localhost
event - build page: /menu_accounting/ReportGross
wait - compiling...
error - ./node_modules/react-export-excel/node_modules/xlsx/xlsx.js
Module not found: Can't resolve 'fs' in '/home/ahmadb/repos/lorry-erp/node_modules/react-export-excel/node_modules/xlsx'
Could not find files for /menu_accounting/ReportGross in .next/build-manifest.json
I had the same problem, the solution for me was this:
Install this packages (if you installed, ignored this)
npm install file-saver --save
npm install xlsx
npm install --save-dev json-loader
Add this to your nextjs.config.js
const path = require('path')
module.exports = {
...
//Add this lines
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
}

Running webpack throws 'Callback was already called' error

I just started learning webpack to manage dependencies in my project. I am trying to use it to build bundles for my typescript and javascript files. For the typescript files, I am using the ts-loader plugin for handling it. For CSS, I am using the mini-css-extract and an optimize-css-assets plugin. When I try to run webpack, I get the following error and I am not able to figure out what might be causing this error.
user#system spl % npm run build
> spl#1.0.0 build /Users/user/Downloads/spl
> webpack --config webpack.config.js
/Users/user/Downloads/spl/node_modules/neo-async/async.js:16
throw new Error('Callback was already called.');
^
Error: Callback was already called.
at throwError (/Users/user/Downloads/spl/node_modules/neo-async/async.js:16:11)
at /Users/user/Downloads/spl/node_modules/neo-async/async.js:2818:7
at processTicksAndRejections (internal/process/task_queues.js:79:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! spl#1.0.0 build: `webpack --config webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the spl#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/user/.npm/_logs/2020-05-14T14_23_32_985Z-debug.log
The following is my webpack.config file that I am using to build my dist files.
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = {
mode: 'production',
entry: "./static/js/index.js",
output: {
filename: "bundle.[contentHash].js", // File name with hash, based on content
path: path.resolve(__dirname, 'dist')
},
optimization: {
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin(),
new HtmlWebpackPlugin({
template: "./static/index.html",
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true
}
})
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contentHash].css"
}),
new CleanWebpackPlugin(),
],
module: {
rules: [
{
test: /\.html$/,
use: [ "html-loader" ]
},
{
test: /\.[tj]s$/,
use: "ts-loader",
exclude: /(node_modules|tests)/
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
],
},
resolve: {
alias: {
src: path.resolve(__dirname, 'src'),
static: path.resolve(__dirname, 'static'),
},
extensions: [ '.ts', '.js' ]
}
}
I had the same issue and I realized that I was importing CSS file from my index.html file:
<link rel="stylesheet" href="./css/main.css">
although the CSS file should have been imported from entry file (index.js) using import:
import '../css/main.css';
so I deleted the line <link rel="stylesheet" href="./css/main.css"> and solved the problem.
You can see your HTML file and check if there are any assets imported from your HTML file. I hope it helped.
tl;dr: Upgrading webpack to a newer version solved it for me.
I went into node_modules/neo-async/async.js and modified the onlyOnce so that it gives a bit more descriptive stack trace like this:
/**
* #private
* #param {Function} func
*/
function onlyOnce(func) {
const defined = new Error('onlyOnce first used here')
return function(err, res) {
var fn = func;
func = () => {
console.error(defined);
throwError();
};
fn(err, res);
};
}
The stack trace points into webpack’s internal code, which, when I upgraded to the latest version, solves this issue.
I ran into this issue and was able to determine that the cause was circular dependencies in Typescript, not outdated dependencies as suggested by other answers here. This error appeared when I refactored code from import MyClass from "folder/file" into import { MyClass } from "folder".
I only considered this possibility after reading this post about differences in semantics between export default and other types of exports.
I had this issue and it was related to a recent downgrade someone had made to mini-css-extract-plugin. We are using pnpm, so this answer is specific to that. I had to delete the pnpm-lock.yaml file in the module I was trying to run out of spring boot dashboard in VSCode. This file is generated if it is missing, but for us anyway, it was committed to the repo. If that doesn't work for you, you might also consider deleting the npm-cache and .pnpm-store dirs. The locations of those files are configured in the .npmrc file in your user's home directory.
For me, the issue came after upgrading css-loader. Downgrading it back to the original version did the trick for me
diff --git a/package.json b/package.json
index 7151c509..b0eba48b 100644
--- a/package.json
+++ b/package.json
## -111,7 +111,7 ##
"webpack-merge": "^4.1.3"
},
"devDependencies": {
- "css-loader": "^6.5.1",
+ "css-loader": "^1.0.0",

Unable to implement webpack in project with node-red

I am trying to implement webpack in my project which contains node-red. However, I keep getting the following warning. Please suggest how to solve this error -
WARNING in ./node_modules/node-red/red/runtime/storage/localfilesystem/projects/git/node-red-ask-pass.sh 1:26
Module parse failed: Unexpected token (1:26)
You may need an appropriate loader to handle this file type.
> "$NODE_RED_GIT_NODE_PATH" "$NODE_RED_GIT_ASKPASS_PATH" "$NODE_RED_GIT_SOCK_PATH" $#
|
# ./node_modules/node-red/red/runtime/storage sync ^\.\/.*$ ./localfilesystem/projects/git/node-red-ask-pass.sh
# ./node_modules/node-red/red/runtime/storage/index.js
# ./node_modules/node-red/red/runtime/index.js
# ./app.js
My webpack.config.js is -
const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()],
entry: './app.js',
output: {
path: path.resolve(__dirname, './output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js','.json', '.sh'],
modules: [
'node_modules'
],
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
}
]
}
};
For Webpack, every file is a .js. In order to handle other extensions, like .css or .sh, you're supposed to use a loader, like you did with css-loader, that will tranform CSS rules into JS.
The issue you're facing is that you've got an import chain (./app.js -> .../index.js -> .../index.js -> .../node-red-ask-pass.sh), so Webpack will, at some point, will import a .sh file, but will throw an error because shell code is obviousouly invalid JavaScript. that is why you're seeing the error that you have.
By the way, I couldn't reproduce the issue you're facing:
npm init -y
npm i node-red
# ./node_modules/node-red/red is not a directory
So it was probably a node-red bug. Update the package to the latest version.

Using Benchmarkjs with Webpack and Babel

I'm trying to get some basic benchmark tests working and am having trouble figuring out the right configuration. I'm trying to use Benchmarkjs with webpack and babel to transpile my code to es5. I created a benchmarks.webpack.js as an entry point which looks like this:
var context = require.context('./src/js', true, /-benchmark\.js$/);
context.keys().forEach(context);
module.exports = context;
I then have a benchmark file that I want to run (test-benchmark.js):
import benchmark from 'benchmark';
import benchmarks from 'beautify-benchmark';
let suite = new benchmark.Suite;
suite.add('RegExp#test', function() {
/o/.test('Hello World!');
})
.add('String#indexOf', function() {
'Hello World!'.indexOf('o') > -1;
})
.on('cycle', function(event) {
benchmarks.add(event.target);
})
.on('complete', function() {
benchmarks.log();
})
.run();
I updated my webpack build to try and transpile the benchmarks:
_.assign(config, {
devtool: 'eval-cheap-module-source-map',
output: {
path: path.join(__dirname, 'build/benchmark'),
filename: 'benchmark.js',
publicPath: '/'
},
entry: [
'./benchmarks.webpack.js'
],
plugins: [
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel?stage=0'],
include: path.join(__dirname, 'src/js')
},
]
},
});
Finally, I want to be able run this from an npm script:
"scripts": {
"bench": "webpack --config webpack.bench.config.js && node build/benchmark/benchmark.js"
},
However, I'm getting warnings that the result of the benchmark dependency is an expression and there no suitable loaders for the .json, .txt, etc files. I tried hacking up Benchmarkjs to export correctly but was not successful.
WARNING in ./~/benchmark/benchmark.js
Critical dependencies:
1122:34-49 the request of a dependency is an expression
# ./~/benchmark/benchmark.js 1122:34-49
WARNING in ./~/benchmark/package.json
Module parse failed: /home/bill/dev/levelstory/react-client-redux/node_modules/benchmark/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "name": "benchmark",
| "version": "1.0.0",
| "description": "A benchmarking library that works on nearly all JavaScript platforms, supports high-resolution timers, and returns statistically significant results.",
# ./~/benchmark ^\.\/.*$
WARNING in ./~/benchmark/LICENSE.txt
Module parse failed: /home/bill/dev/levelstory/react-client-redux/node_modules/benchmark/LICENSE.txt Line 1: Unexpected number
You may need an appropriate loader to handle this file type.
| Copyright 2010-2012 Mathias Bynens <http://mathiasbynens.be/>
| Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
| Modified by John-David Dalton <http://allyoucanleet.com/>
# ./~/benchmark ^\.\/.*$
Looks like benchmark does something special with require. That messes it up for Webpack. It has the following lines:
var freeRequire = typeof require == 'function' && require;
...
function req(id) {
try {
var result = freeExports && freeRequire(id);
} catch(e) { }
return result || null;
}
If you comment out the function contents, the error goes away. Given it's not ideal to patch around it this way I would poke the benchmark guys about this directly instead. Perhaps there's something we're missing.

Resources