babel-plugin-syntax-dynamic-import does not transpile - reactjs

I think I correctly configured babel-plugin-syntax-dynamic-import but it would still not transpile my dynamic import.
Node: v8.11.3
package.json:
...
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-loader": "^7.1.5",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
...
"webpack": "^4.16.5",
"webpack-bundle-analyzer": "^2.13.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
},
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js --open --hot --progress",
...
},
"dependencies": {
"babel-core": "^6.26.3",
"babel-polyfill": "^6.26.0",
...
"react-loadable": "^5.5.0",
"whatwg-fetch": "^2.0.4"
}
webpack.config.js:
...
{
test: [/\.js$/, /\.jsx?$/],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
...
.babelrc
{
"presets": ["env", "react", "stage-3"],
"plugins": ["syntax-dynamic-import"]
}
AsyncComp.jsx:
import React from 'react';
import Loadable from 'react-loadable';
const Loading = () => (<div>Loading...</div>);
const LoadableComponent = Loadable({
loader: () => import('./CompRaw'),
loading: Loading,
})
export default class AsyncComp extends React.Component {
render() {
return <LoadableComponent />;
}
}
executing yarn dev results in:
/home/somepath/src/components/AsycnComp.jsx
7:17 error Parsing error: Unexpected token import
Why is the dynamic import() not transpiled? How can I fix it?

Ah okay! I think you also need react-loadable/babel. See the discussion here: https://github.com/jamiebuilds/react-loadable/pull/35#issuecomment-337156641

The configuration is good and the error originates from using the eslint-loader but not installing babel-eslint plugin which would enable support for dynamic imports.
This solved the issue
yarn add babel-eslint -D
.eslintrc
{
...
"parser": "babel-eslint"
}

Related

Use alt with react in ES6

I'm trying to use alt with React and code an Action in ES6 style:
import alt from '../alt';
class LoginActions {
login() {
alert('oi');
}
}
export default alt.createActions(LoginActions);
My .babelrc is using class transformation plugin:
// without options
{
"plugins": ["transform-class-properties"]
}
My package.json is configured with babel and webpack
{
"name": "npm-yarn-babel-webpack",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"babel-core": "6",
"babel-loader": "7",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^1.0.1",
"node-sass": "^4.10.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.25.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
},
"dependencies": {
"alt": "^0.18.6",
"react": "^16.6.3",
"react-dom": "^16.6.3"
},
"scripts": {
"build": "webpack -p",
"dev": "webpack-dev-server --hot --inline"
}
I Have a component Hello World:
import React, { Component } from 'react';
import LoginActions from './LoginActions';
export class HelloWorld extends Component {
render() {
return (
<div className="hello-world">
<h1>Hello World</h1>
</div>
);
}
}
export default HelloWorld;
I'm running as:
yarn run dev
If I do not import LoginActions, it works, when I import, it compiles, but it does not work.
If I a run with react-scripts it show me an error that alt can understand ES6 class definition.
What Am I doing wrong?
Your babel-loader is only configured for .jsx files. You need to configure it for .js file too which alt.js is. To do that use the regex /\.jsx?/
{
test: /\.jsx?/,
use: {
loader: 'babel-loader',
options: { presets: ['react', 'es2015'] }
}
},

Missing class properties transform when Webpack presets:"env"

I'm testing React project on webpack-dev-server. I want to use classfield syntax but got an error at state init.
client:162 ./src/containers/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Missing class properties transform.
2 |
3 | class App extends Component {
4 | state = {
| ^
5 | count: 0
6 | }
7 | // constructor(props) {
I found solution that presets to be this "presets": ["es2015", "stage-0", "react"]. But I'm using "env" presets. I thought "env" presets support all babel-stages. Do I have to change presets?
App.js
class App extends Component {
state = {
count: 0
}
render() {
return (
<div>
<input defaultValue={this.state.count} />
</div>
);
}
}
export default App;
package.json
{
"name": "redux",
"version": "1.0.0",
"description": "",
"main": "counter.js",
"dependencies": {
"#types/react": "^16.4.14",
"babel": "^6.23.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0",
"http": "0.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.9"
},
"scripts": {
"devserver": "webpack-dev-server --open --progress"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.24.1"
}
}
.babelrc
{
"presets": ["env", "react"],
"plugins": ["transform-class-properties"]
}
.webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname),
exclude: /(node_modules)|(dist)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
}
Try this:
.babelrc
{
"presets": ["env", "react", "stage-2"]
}
package.json
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
...
When using the .babelrc file, in the webpack.config.js, we can simply config like this:
{
test: /\.js$/,
use: ['babel-loader']
}
Hopefully, that helps.

Mocha/ Enzyme doesn't Recognise jsx

My goal is to test reactjs code written with jsx with mocha as test runner, enzyme and chai. Currently I'm getting an unexpectet token error.
I already try the solution inside mocha-will-not-recognise-jsx but it didn't solves my error.
Package.json
{
"scripts": {
"test": "mocha --recursive application/**/*.spec.js* --compilers js:babel-register",
},
[
...
],
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0",
"chai": "^4.1.2",
"enzyme": "^2.9.1",
"html-webpack-plugin": "^2.30.1",
"mocha": "^3.5.0",
"standard": "^10.0.3",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
}
}
Webpack modules
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'env']
}
}]
}
Error Message
D:\Development\game-of-life\node_modules\babel-core\lib\transformation\file\index.js:59
0
throw err;
^
SyntaxError: D:/Development/game-of-life/application/src/components/app/App.spec.jsx: U
nexpected token (8:28)
6 | describe('App', () => {
7 | it('renders "<div>Application is running</div>"', () => {
> 8 | const wrapper = shallow(<App />)
| ^
9 | expect(wrapper.contains(<div>Application is running</div>)).to.be.eql(true)
10 | })
11 | })
Did I forgot to install a package or does a newer version of a package works different to an older version of the package because I already realized with equal dependencies a react-enzyme project.
I found two posible ways to solve the problem
.babelrc
Adding a .babelrc with the configureation presets: ['react', 'env'].
webpack
Adding a configuration (babelrc: false) to avoid .babelrc and to use the webpack configuration

React Webpack in Production Error #105

I'm kind of desperate here.
I'm working on a React application and use webpack to compile my bundle.js.
The problem is when i try to compile it for "production" i end up with a really nasty error :
"Minified React error #105; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=105&args[]=HardwareKeyboardArrowDown for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
Followed by a bunch of
"Uncaught TypeError: Cannot read property '__reactInternalInstance$qw6tjofxg1o' of null"
When i set my node.env to developement ('NODE_ENV': JSON.stringify('developement') ), it's working fine.
The link in the error says : "A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object" but i don't have any problem in dev mode, so i don't think its coming from my code and i can't find where i should look to solve this problem since dev mode doesn't tell anything more to me...
Here are my webpack config & package.json :
const webpack = require('webpack');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const config = {
entry: [
'./src/app/app.js'
],
// Render source-map file for final build
devtool: 'source-map',
debug: true,
// output config
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},
plugins: [
// Define production build to allow React to strip out unnecessary checks
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
// Minify the bundle
new webpack.optimize.UglifyJsPlugin({
compress: {
// suppresses warnings, usually from module minification
warnings: false,
},
}),
// Allows error warnings but does not stop compiling.
new webpack.NoErrorsPlugin(),
// Transfer Files
],
module: {
loaders: [
{
test: /\.js$/, // All .js files
loaders: ['babel-loader'], // react-hot is like browser sync and babel loads jsx and es6-7
exclude: [nodeModulesPath],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
include: /flexboxgrid/
},
{
test: /\.json$/, loader: "json-loader",
},
{ test: /\.scss?$/,
loader: 'style!css!sass',
include: path.join(__dirname, 'src', 'styles') },
{ test: /\.png$/,
loader: 'file' },
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file'}
],
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.json']
}
},
};
module.exports = config;
{
"name": "material-ui-example-webpack",
"version": "0.16.0",
"description": "Sample project that uses Material-UI",
"repository": {
"type": "git",
"url": "https://github.com/callemall/material-ui.git"
},
"scripts": {
"start": "webpack-dev-server --config webpack-dev-server.config.js --host $IP --port $PORT --hot --progress --inline --colors",
"clean-public": "npm run remove-public && mkdir public",
"remove-public": "node_modules/.bin/rimraf ./public",
"build:html": "babel-node tools/buildHtml.js",
"heroku-prebuild": "npm install && npm-run-all clean-public build:html",
"heroku-postbuild": "babel-node tools/build.js",
"prod-start": "babel-node tools/publicServer.js"
},
"private": true,
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-2": "^6.18.0",
"html-webpack-plugin": "^2.24.1",
"npm-run-all": "1.8.0",
"redux-devtools": "^3.4.0",
"redux-devtools-dock-monitor": "^1.1.2",
"redux-devtools-log-monitor": "^1.3.0",
"rimraf": "2.5.2",
"transfer-webpack-plugin": "^0.1.4",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"axios": "^0.16.1",
"babel-cli": "6.8.0",
"babel-loader": "^6.2.8",
"babel-polyfill": "6.8.0",
"babel-preset-es2015": "6.6.0",
"babel-preset-react": "6.5.0",
"babel-preset-stage-2": "^6.24.1",
"cheerio": "^0.20.0",
"colors": "1.1.2",
"compression": "^1.6.1",
"css-loader": "^0.27.3",
"express": "^4.15.2",
"json-loader": "^0.5.4",
"lint": "^1.1.2",
"material-ui": "^0.17.1",
"ncp": "^2.0.0",
"npm-run-all": "1.8.0",
"open": "0.0.5",
"react": "^15.4.1",
"react-component-queries": "^2.1.1",
"react-dom": "^15.4.1",
"react-fittext": "https://github.com/gianu/react-fittext",
"react-flexbox-grid": "^1.0.2",
"react-html-parser": "^1.0.3",
"react-masonry-component": "^5.0.5",
"react-redux": "^5.0.4",
"react-responsive": "^1.2.7",
"react-router": "^2.0.0-rc5",
"react-router-dom": "^4.0.0",
"react-sizeme": "^2.3.1",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.6.0",
"redux-form": "^6.6.3",
"redux-promise": "^0.5.3",
"rimraf": "2.5.2",
"serve-favicon": "^2.3.0",
"style-loader": "^0.16.0",
"transfer-webpack-plugin": "^0.1.4",
"webpack": "^1.13.3"
}
}
buildHtml script :
import fs from 'fs';
import cheerio from 'cheerio';
import colors from 'colors';
/*eslint-disable no-console */
console.log("buildHTML.js start");
fs.readFile('src/index.html', 'utf8', (err, markup) => {
if (err) {
return console.log(err);
}
const $ = cheerio.load(markup);
$('head').prepend('');
fs.writeFile('public/index.html', $.html(), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log('index.html written to /public'.green);
});
});
And then build.js
/*eslint-disable no-console */
import webpack from 'webpack';
import webpackConfig from '../webpack-production.config';
import colors from 'colors';
import ncp from 'ncp';
process.env.NODE_ENV = 'production';
console.log("build.js start");
//Static files to import in /public (images/css)
var source = [["src/images","public/images"],["src/css","public/css"]];
function copyStaticFiles(path){
ncp(path[0], path[1], function (err) {
if (err) {
return console.error(err);
}})
}
console.log('Generating minified bundle for production via Webpack...'.blue);
webpack(webpackConfig).run((err, stats) => {
if (err) { // so a fatal error occurred. Stop here.
console.log(err.bold.red);
return 1;
}
const jsonStats = stats.toJson();
if (jsonStats.hasErrors) {
return jsonStats.errors.map(error => console.log(error.red));
}
if (jsonStats.hasWarnings) {
console.log('Webpack generated the following warnings: '.bold.yellow);
jsonStats.warnings.map(warning => console.log(warning.yellow));
}
console.log(`Webpack stats: ${stats}`);
source.forEach(copyStaticFiles);
console.log('Your app has been compiled in production mode and written to /public.'.green);
return 0;
});
I don't even know where to start and i can't find any documentation about this kind of errors.
I can provide more informations if needed.
Thanks for reading me
Ok so i dont have a object with a HardwareKeyboardArrowDown so i went looking in my dependencies and i found that it came from the matérial-ui dependency.
I forced the version 17.4 in my package.json and it worked !
The message gave you the name of the function (component) that returns the invalid object. HardwareKeyboardArrowDown.
So you should look at the return of its render function and make sure you return a valid React element (or null)
That means no undefined, array etc..

unexpected token import during npm start in react

I am learning react and created a mock up project but when I run the project I get the following error,my webpack.config.js file code is as follows,
module.exports = {
entry: './client.js',
output: {
filename: 'bundle.js',
path: 'public'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}]
}
};
my package.json file,
{
"name": "universal-react",
"version": "0.0.0",
"description": "Universal React web application.",
"scripts": {
"start": "webpack && node server.js",
"dev": "npm-run-all --parallel watch:*",
"watch:webpack": "webpack -w",
"watch:server": "nodemon --ext js,jsx --ignore public/ server.js"
},
"main": "server.js",
"keywords": [
"universal",
"react"
],
"dependencies": {
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4",
"babel-preset-react": "^6.5.0",
"babel-register": "^6.9.0",
"express": "^4.13.4",
"marked": "^0.3.6",
"react": "^15.0.2",
"react-dom": "^15.0.2",
"react-redux": "^4.4.6",
"react-router": "^2.8.1",
"redux": "^3.6.0",
"webpack": "^1.13.1"
},
"devDependencies": {
"nodemon": "^1.11.0",
"npm-run-all": "^3.1.2"
}
}
error message is as follows,
/home/user/Documents/test/src/routes/index.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at loader (/home/user/Documents/src/node_modules/babel-register/lib/node.js:144:5)
Could anyone suggest me where i am wrong?
You have not installed babel-preset-es2015 as per your package.json.
"babel-preset-es2015": "^6.9.0",
try installing it via
npm install --save babel-preset-es2015
Also add
"babel": "^6.5.2",
"babel-cli": "^6.9.0"
and a .babelrc file in project root parallel to your package.json
with following content.
$ cat .babelrc
{
"presets": [
"es2015",
"react"
]
}
and then run npm install then webpack again.

Resources