React Hot Module Reloader preventing mocha tests from running - javascript

I have a React project which is running the react-transform-hmr hot module reloader, and all was running fine until I implemented mocha tests.
When I run the tests I get the following error:
throw new Error('locals[0] does not appear to be a module object
with Hot Module ' + 'replacement API enabled. You should disable
react-transform-hmr in ' + 'production by using env section in Babel
configuration. See the ' + 'example in README:
https://github.com/gaearon/react-transform-hmr');
I have googled this, and found some information mentioning moving the hot module reloading setup out of the .babelrc file and into the Webpack config, which I did, and the tests ran fine, but then the Hot Module Reloading wasn't working.
After playing around, and not getting both to work together, I have reverted and thought I would ask for some help as I am truly stuck. Any ideas what I can do?
My babel config is as follows:
{
"presets": ["react", "es2015", "stage-1"],
"env": {
"development": {
"plugins": [
["transform-object-rest-spread"],
["transform-react-display-name"],
["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}, {
"transform": "react-transform-catch-errors",
"imports": ["react", "redbox-react"]
}]
}]
]
},
"production": {
"plugins": [
["transform-object-rest-spread"],
["transform-react-display-name"]
]
}
}
}
And my webpack config is as follows:
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
}
]
}
Thank you :)

Got this working with the following in the package.json:
"test": "export NODE_ENV=testing|| set NODE_ENV=testing&& mocha --compilers js:babel-core/register --require ./tests/test-helper.js \"./tests/**/*#(.js|.jsx)\"",
This was taken from here.

Related

How to transpile an npm dependency to es5 with babel and webpack?

I have to make our website compatible for internet explorer, and it’s quite tricky, as the browser doesn’t understand es6 (arrow functions and the like). I’ve been trying to upgrade webpack and tweak the webpack and babel config to fit our needs. This works great for our own source files, but doesn’t in the node_modules folder. The syntax is not IE compatible if we don’t include it in our babel transpiling, but it also fails if we do transpile the specific node_modules folder that fails (a dependency within the webpack-hot-middleware dependency), giving an error of Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead. I’m hoping I just have the wrong babel or webpack settings here, but I've been scraping the interwebz for answers for a while but haven't quite found the solution yet.
I'm using webpack 5 and babel-loader. I have a .babelrc and a webpack.config.js file, here is a snippet from the latter while I try to transpile the failing node_module package:
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: [
{
and: [/node_modules/],
not: [
path.resolve(
__dirname,
"node_modules/webpack-hot-middleware/node_modules/ansi-regex"
)
]
}
],
options: {
babelrc: false,
presets: [
"#babel/preset-react",
["#babel/preset-env", {
"corejs": { "version": 3 },
"useBuiltIns": "usage",
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1",
"ie": "10"
},
}]],
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-transform-arrow-functions"
]
}
},
[...]
]
}

Upgrading Node JS and ERR_REQUIRE_ESM: Must use import to load ES Module: 'inheritsloose.js' of Babel Runtime

The following error is emitted in my Node JS/React JS application after upgrading Node JS to v.12. I'm currently using #babel/core 7.10.1. How should this error be resolved?
Here is my babel.config.js:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'#babel/preset-react',
'#babel/preset-typescript',
],
plugins: [
'#babel/plugin-proposal-class-properties',
['#babel/plugin-proposal-decorators', { legacy: true }],
'#babel/plugin-proposal-export-default-from',
'#babel/plugin-proposal-export-namespace-from',
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-transform-react-constant-elements',
'#babel/plugin-transform-react-inline-elements',
],
ignore: ['node_modules', 'build'],
};
Try to remove "type": "module" from package.json.
I've spend many hours with no luck and finally found this commend in discussion:
https://github.com/manuelbieh/geolib/issues/208#issuecomment-556994420
You have ignore: ['node_modules', 'build'], maybe, that's the reason?
I had nested package.json files within my application. These package.json files defined dependencies. I believe that parts of the app were being transpiled with different versions of Babel. I flattened my application and removed the nested package.json files. This action solved my problem.

ThreeJS module is not transpiled by Babel

Im using Three.js as a module, transpiling a code using Babel, packing with WebPack. The problem is that even all the other code is properly transpiled, the three.js module is not and still contains ES6 syntax. Which causes problems in IE11.
.babelrc
{
"presets": [
[
"#babel/preset-env" , {
"targets": {
"ie": "11"
}
}]
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-classes"
]
}
webpack.config
module: {
rules: [
{
test: /\.js$/,
//exclude: /node_modules/,
loaders: ['babel-loader']
},
...
Here I commented out to exclude the node_module folder, but even with that the problem still persists
Any idea what is wrong and how I could get transpiled Threejs module? Thanks a lot
This worked for me:
In the webpack config, set the exclude property like this:
exclude: /node_modules\/(?!(three)\/).*/,.
This forces babel to transpile three no matter what.
Reference: stackoverflow
Cheers

How to setup VSCode to debug a webpack bundled nodejs server

I have a nodejs express application, which I'm attempting to bundle with webpack 4 (plus babel 7.1.0). I've followed some of the setup from these two articles:
Webpack Javascript Bundling for Both Front-end and Back-end (nodejs)
Creating a server bundle with Webpack for universal rendering
I can build and run the server once bundled, but I'd like to be able to debug it using VS Code's debug environment.
I've tried the following combination of webpack and vscode config, but it doesn't set breakpoints or let me step into the code.
.vscode/launch.json
{
"type": "node",
"request": "launch",
"name": "bundle-server.js",
"program": "${workspaceFolder}\\bundle-server.js",
"sourceMaps": true,
"smartStep": true,
}
webpack-server.config.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: "node",
entry: "./server.js",
output: {
path: path.resolve(__dirname, "./"),
filename: "bundle-server.js",
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader"
}
],
},
externals: [nodeExternals()],
devtool: 'inline-source-map',
};
What am I missing? Is it even possible to debug directly from VSCode? I'd like to be able to step over the original source files so I can have a quick debug-edit-rerun loop.
Seems related to this: Debug webpack bundled node ts with Visual Studio Code.
In your launch configs, you are providing output file of webpack as the program to debug.
To Build:
You can instead use program as path to your webpack runner. Ex:
"program": "${workspaceFolder}/node_modules/webpack/bin/webpack.js" // Or CLI
And then you should provide the file as an argument you want to run with webpack. Ex:
"args": [
"--config", "./some/dir/webpack.config.js"
]
To Run:
Follow the same procedure with a different program
"program": "${workspaceFolder}/node_modules/webpack-dev-server/bin/webpack-dev-server",
"args": [
"--config",
"webpack-server.config.js",
"--hot",
"--progress"
]
Try these two configurations. Should build the project first and then automagically attach the node inspector via VSCode. I've just tried it on my project and it seems to be working well.
I'm doing the same thing you are - building a project using Webpack and Babel
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Server",
"program": "${workspaceFolder}\\bundle-server.js",
"preLaunchTask": "build"
}
]
}
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "npm",
"script": "build",
"problemMatcher": [
]
}
]
}

Node JS Webpack Babel with async

When trying to compile my server-side code, I get the following error:
Module parse failed: (...babel-loader-path)?{"presets":["es2015-node4","es2015"]} (...) Unexpected token (86:6)
You may need an appropriate loader to handle this file type.
This error seems to be caused by an Async function that I am trying to import. Do I need to change my webpack configuration?
My webpack config file:
const webpack = require('webpack');
module.exports = {
target: 'node',
entry: ['./server/index.js', './node_modules/webpack/hot/poll?1000'],
output: {
path: './dist',
filename: 'server.bundle.js',
libraryTarget: 'commonjs',
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
externals: [/^[a-z]/],
module: {
loaders: [{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015-node4', 'es2015'],
},
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015-node4', 'es2015'],
},
}
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devtool: 'source-map',
};
If you are using Webpack to compile your Node code, then that is not a good approach. You should simply use babel-node which is an amazing way to transpile your node code.
For that in your package.json do the following
"scripts": {
"dev": "node_modules/.bin/nodemon --exec babel-node server/index.js",
"prestart": "node_modules/.bin/babel server --out-dir dist",
"start": "node dist/index.js"
},
"devDependencies": {
"#babel/cli": "^7.0.0-beta.40",
"#babel/core": "^7.0.0-beta.40",
"#babel/node": "^7.0.0-beta.40",
"#babel/preset-env": "^7.0.0-beta.40",
"#babel/preset-stage-2": "^7.0.0-beta.40",
"nodemon": "^1.11.0"
}
In your .babelrc file, do the following.
{
"presets": [
"#babel/preset-env",
"#babel/preset-stage-2"
]
}
Then in your project directory create a folder called server and in that folder create a file called index.js which creates your node http server.
For a reference have a look at Babel-Node Documentation
Or have a look at this amazing small tutorial kind of example created by the awesome folks at Babel Example Node Server Using Babel-Node
P.S: In the package.json file the npm run dev watches your code and npm start commands compiles your code ready to be shipped for production.
There seems to be a mis-understanding with regard to the babel preset usage. The preset you want is not the target version of javascript you want to output. For that you need to set target appropriately. Instead you needed the preset that corresponds to the version of javascript you are writing in. The presets are collections of transformers that instruct babel how to deal with specific javascript constructs.
In babel <=6 you need either: es2017 or transform-async-to-generator presets to use the async keyword. After babel 7 the recommendation is to use:
{
"presets": ["#babel/preset-env"]
}
This allows babel to support all modern java-script syntax's that have been finalized. It will then transpile to whatever syntax your target setting indicates. I personally would use a browserslist query in package.json for this so other tools like postcss automatically pick up the same target information.

Categories

Resources