Jest test 'unexpected token export' - javascript

I'm trying to get my jest tests to run. I am getting the error SyntaxError: Unexpected token export at the line export default configureStore..specifically on the word 'export'. To me this suggests redux-mock-store is not being transpiled by Babel, so how can I force this with Jest? I'm using jest-webpack.
ContractsActions.test.js
import * as contractsActions from './contractsActions';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
const store = mockStore({})
return store.dispatch(contractsActions.fetchAllContracts()).then(() => {
//Do something
})
});
package.json
...
"scripts": {
"test": "jest-webpack",
...
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
...
webpack.config.js
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015', 'react', 'stage-2']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
}
},

I ended up fixing this problem by creating a separate .babelrc file, instead of trying to set the babel configuration settings in package.json. I'm sure there are other steps I tried that may have contributed but this seemed to be the one that fixed it.
.babelrc
{
"presets": [["es2015", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}

Take a look at the package.json from that package:
https://github.com/arnaudbenard/redux-mock-store/blob/master/package.json
You can see it offers different entry points:
"main": "dist/index-cjs.js",
"module": "dist/index-es.js",
"js:next": "dist/index-es.js",
"browser": "dist/index.min.js",
Check if your node_modules/redux-mock-store has a dist folder. If not, start the build that suits your requirements (also listed in package.json):
"build:cjs": "babel src --out-file dist/index-cjs.js",
"build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f umd -c -i src/index.js -o dist/index-umd.js",
"build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -f umd -c -i src/index.js -o dist/index-umd.min.js",
"build:es": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f es -c -i src/index.js -o dist/index-es.js",
"build": "npm run build:umd && npm run build:umd:min && npm run build:es && npm run build:cjs",
I don't know which of those versions buildable would be the right one for you, but I assume one of them will be. At worst, start npm i && npm run build:cjs in node_modules/redux-mock-store and resort to CommonJS require syntax:
const configureMockStore = require('redux-mock-store/dist/index-cjs.js');
Really hope this solves your problem, at least these are the steps I would try.

Related

Vitejs. Running a script for a specific task

I'm using Vite. I installed the npm plugin called 'vite-plugin-zip-file' in order to archive the dist folder. How can I run a separate from 'build' script in package.json specifically for this task?
vite.config.js below
import { defineConfig } from 'vite';
import { resolve } from 'path';
import { viteZip } from 'vite-plugin-zip-file';
export default defineConfig({
build: {
outDir: 'build',
},
plugins: [
viteZip({
folderPath: resolve(__dirname, 'build'),
outPath: resolve(__dirname),
zipName: 'Test.zip',
}),
],
});
package.json 'scripts' (I don't know what to write in 'zip' here)
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
"zip": ?
},
I tried adding the environmental variable, but I don't know exactly how to do it. So, there's probably another better way.

How to put React in production mode?

I tried using the solution from here but the icon is still read indicating dev mode.
Here is my current file with updates from the answer below:
const path = require('path');
const SRC_DIR = path.join(__dirname, '/client-react/src');
const DIST_DIR = path.join(__dirname, '/client-react/dist');
const webpack = require('webpack')
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: 'bundle.js',
path: DIST_DIR
},
plugins: [
new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production')} })
],
module: {
loaders: [
{
test: /\.jsx?/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
plugins: ["transform-object-rest-spread", "transform-class-properties"],
presets: ['react', 'es2015']
}
}
]
}
};
If you use Webpack 4, you don't need to change webpack.config.js. It remains the same in both development and production modes.
The only thing needed is in your package.json:
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production"
}
Having this, to create a development bundle:
npm run dev
Production bundle:
npm run build
When you want to build your app in production mode, you should use webpack production shortcut. Like this:
webpack -p
This will enable webpack optimize options to minify your JS. See more detailed explanation of webpack flags on this SO answer.
Webpack plugins need to be put under the plugins key in module.exports.
https://webpack.github.io/docs/using-plugins.html#built-in-plugins
Try this:
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
]
}
Had the same error so to fix it I did this:
package.json
"scripts": {
"build": "NODE_ENV=production webpack --progress --colors",
"start": "NODE_ENV=development webpack-dev-server --progress --colors"
}
webpack.config.js
const env = process.env.NODE_ENV
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
})
]
}
It should work for sure.
Here I have some configuration that you can try to optimize your build.
This worked for me: run npm run build followed by npm install -g serve and serve -s build

Making export default work with Babel, webpack and Node.js

I can't figure out why my code doesn't work.
I am building a ES6 style class and want to export it to be able to use it somewhere else in the server side. I put the code into a file called PlayerManager.jsin the server folder.
I put my client code in the src folder. And my server code in my server folder and server.js outside of server folder.
Here is the directory structure:
Root
- dist
- node_modules
- public
- server
- src
server.js
webpack.base.js
webpack.dist.js
package.json
.babelrc
PlayerManager.js file:
class PlayerManager {
constructor() {
if (! PlayerManager.instance) {
this.playerList = {};
this.bulletList = {};
this.initPack = {player: [], bullet: []};
this.removePack = {player: [], bullet: []};
PlayerManager.instance = this;
}
return PlayerManager.instance;
}
resetData() {
this.initPack.player = [];
this.initPack.bullet = [];
this.removePack.player = [];
this.removePack.bullet = [];
}
}
const instance = new PlayerManager();
Object.freeze(instance);
export default instance;
However, when I use npm run dev which runs node server.js it throws an error saying
export default instance;
^^^^^^
SyntaxError: Unexpected token export
at Object.exports.runInThisContext (vm.js:53:16)
Here is the configuration for babel in webpack:
const path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
main: './src/main'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js'
},
plugins: [
new CopyWebpackPlugin([
{ from: 'public/img',
to: 'static' },
{ from: 'public' }
])
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
//include: path.join(__dirname, 'src')
exclude: [
path.resolve(__dirname, "node_modules"),
],
},
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=90000' }
]
},
resolve: {
extensions: ['', '.js']
}
};
In .babelrc:
{
"presets": [
"es2015"
],
"sourceRoot": "./src"
}
In my package.json file:
"scripts": {
"build": "npm run lint && npm run release",
"lint": "./node_modules/.bin/eslint ./src/**/*.js",
"dev": "node server.js",
"release": "NODE_ENV=production webpack --config ./webpack.dist.js --progress",
"test": "./test/*.test.js --compilers js:babel-core/register --recursive --reporter spec"
},
Webpack is a bundler for producing packages that run on the client (in the browser), it is not aware of or concerned with code on the server. (Unless you are doing universal application stuff.)
You will notice too that your npm dev script is simply asking node to load the server.js file, which is (correctly) not mentioned anywhere in your Webpack config.
You are looking for babel-register:
One of the ways you can use Babel is through the require hook. The require hook will bind itself to node’s require and automatically compile files on the fly.
Create an "entry" file that first requires babel-register and then requires your server.js file:
// server-entry.js
require('babel-register')
require('./server.js')
Now change your npm dev script to be node server-entry.js.
______
Aside: it is necessary to create an entry file as babel-register cannot transpile the file in which it is invoked. For example, this would fail:
// server.js
require('babel-register')
export default function () {}

Why does production build of React app (with Webpack and Babel) use wrong development env with HMR, which causes errors?

I'm trying to create a production build of my React project, but it picks the wrong configuration.
In the development version I'm using HMR (Hot Module Replacement). This is configured in .babelrc, under env > development > plugins.
When adding an extra node env > production it seems to be ignored. It's still using the development configuration with HMR, which causes an error:
Uncaught 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
Of course I've checked that information, but everything seems right.
When I removed the HMR plugin from .babelrc's development config, it works, proving it is indeed using the development config instead of production.
Here's my files:
package.json
{
"name": "myproject",
"main": "index.js",
"scripts": {
"serve": "cross-env NODE_ENV=development webpack-dev-server --content-base bin/ --devtool eval --progress --colors --hot --inline",
"deploy": "cross-env NODE_ENV=production BABEL_ENV=production webpack -p --config webpack.production.config.js"
}
//dependencies omitted in this example
}
.babelrc
{
"presets": ["react", "es2015", "stage-0"],
"plugins": [
["transform-decorators-legacy"]
],
"env": {
"development": {
"plugins": [
["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}]
]
},
"production": {
"plugins": []
}
}
}
As you can see in package.json > scripts > deploy, I'm even explicitly setting the BABEL_ENV to 'production'.
Why is this happening? How do I make sure the production build ignores the HMR plugins?
By the way, searching often leads to issue #5 on the React-transform-HMR Github page, which is a long thread without a clear solution.
Edit 2016.03.30: Adding the Babel part of my webpack config on request.
Edit 2016.04.06: Adding whole webpack file on request.
webpack.production.config.js
require('es6-promise').polyfill();
var path = require('path');
module.exports = {
entry: './main.jsx',
context: __dirname + path.sep + 'src',
output: {
path: path.resolve(__dirname, './bin'),
filename: 'index.js'
},
devServer: {
port: 3333
},
module: {
loaders: [
{
test: /\.js(x?)$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: [['transform-decorators-legacy']]
}
},
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.scss$/,
exclude: /(node_modules|bower_components)/,
loader: 'style-loader!css-loader!sass-loader?sourceMap'
}
]
}
};
The only thing that worked for me, is that I wrote -
process.env.NODE_ENV = 'production';
at the beginning of my webpack.config.prod.js file.
It seems that no matter what Babel keeps using the development section of the env value specified in .babelrc. What solved the problem for me, was to use name other than 'development' and set that as the value of BABEL_ENV.
"env": {
"dev": {
"plugins": [
]
},
"production": {
}
}
I use separate conf for development. In plugins I have:
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BABEL_ENV': JSON.stringify('dev')
}
}),
& in shell means that it will run in the background, so maybe your variable declaration is not caught by the build stuff that happens at the same time. The good thing is that you can just prepend the command with the variable declarations.
You could simplify the commands like this:
"serve": "NODE_ENV=development webpack-dev-server --content-base bin/ --devtool eval --progress --colors --hot --inline",
"deploy": "NODE_ENV=production BABEL_ENV=production webpack -p --config webpack.production.config.js"
You can just use the babel-preset-react-hmre.
.babelrc
{
"presets": ["react", "es2015", "stage-0"],
"plugins": [
"transform-decorators-legacy"
],
"env": {
"development": {
"presets": ["react-hmre"]
}
}
}
webpack
{
test: /\.js(x?)$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react', 'stage-0'],
plugins: ['transform-decorators-legacy'],
env: {
development: {
presets: ['react-hmre']
}
}
}
}

Syntax error in ReactJS

I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:
app/App.js
node_modules
index.html
package.json
webpack.config.js
I think that the culprit of the problem is this error message from CLI:
ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
4 | render() {
5 | return (
> 6 | <h1>Hello World</h1>
| ^
7 | );
8 | }
9 | }
The contents of App.js are:
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
React.render(<Hello />, document.getElementById('root'));
Here is the contents of package.json:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^0.14.6"
}
}
And the contents of webpack.config.js are:
module.exports = {
entry: __dirname + "/app/App.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel'
}]
}
};
I launch the application from CLI with the command:
npm start
And when I go to http://localhost:8080 in Dev Tools there is an error message:
GET http://localhost:8080/bundle.js 404 (Not Found)
But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.
I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,
# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev
# Fot JSX support
npm install babel-preset-react --save-dev
then change webpack config
{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
}
}
or instead of using query you can create .babelrc file with content
{
"presets": ["es2015", "react"]
}
also you need install react-dom and use ReactDOM.render instaed or React.render

Categories

Resources