Laravel mix & react - Module build failed on inline import - reactjs

I seem to be having an issue when building my frontend using Laravel mix.
I'm using react-loadable for loading components with promises, as for routing I make use of a declarative config file:
export default [
{
path: '/clients',
exact: true,
auth: true,
component: Loadable({
loader: () => import('./screens/index'),
loading: LoadingComponent,
}),
},
]
When building the js files, I get following error (pointing to the 'i' of import):
ERROR in ./resources/js/modules/clients/routes.js Module build failed:
SyntaxError: Unexpected token (10:26)
When searching the web I came across the fact that, when you wanted to use arrow functions or class properties, you'd need to add a Babel plugin (babel-plugin-transform-class-properties).
So I did add a .babelrc file with following config (it also seems that laravel-mix would automatically make use of the babelrc file):
{
"plugins": ["transform-class-properties"]
}
Still no success.
Any ideas?

Try adding this to your .babelrc file:
{
"presets": [
["es2016"],
"react"
],
"plugins": [
"babel-plugin-transform-class-properties"
]
}

Related

TS Config nested alias for absolute path not working

I'm trying to set up path aliases in my tsconfig.json for a React app bundled with Vite. Here is the relevant part of my tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
...
"paths": {
"*": ["src/*", "node_modules/*"],
"components/*": ["src/components/*"],
"containers/*": ["src/containers/*"],
"pages/*": ["src/constants/*"],
"store/*": ["src/store/*"],
"types/*": ["src/types/*"],
"NestedFolder/*": [
"src/components/NestedFolder/*"
],
}
},
"include": ["src/**/*", "*"]
}
The only issue is with the NestedFolder. When I import this way, everything works:
import { ComponentName } from "components/NestedFolder/types";
However, the nested alias fails:
import { ComponentName } from "NestedFolder/types";
// error
EslintPluginImportResolveError: typescript with invalid interface loaded as resolver
Occurred while linting .../src/components/NestedFolder/canvas/index.ts:1
Rule: "import/namespace"
// error on hover in VS Code
Unable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved
I would like to do nested components because I have several folders that are nested 3-4 levels and it would be nice to have a cleaner view of my imports. Is there a way to do this?
You need to install the vite-tsconfig-paths plugin to set up path aliases using TypeScript and Vite.
If nothing changes and you are using VSCode make sure to restart the TypeScript server by pressing Ctrl+Shift+P or Cmd+Shift+P, typing restart, and then selecting the command: TypeScript: Restart TS server
The accepted answer did not work for me. I found that I had to install the following packages:
npm i eslint-plugin-import eslint-import-resolver-alias eslint-import-resolver-typescript
And then add the following configurations, with the important ingredient being strongly-defined alias paths:
const path = require('path');
module.exports = {
root: true, // important to ensure nested eslint scoping in monorepos
plugins: ['#typescript-eslint', 'import'],
extends: [
'airbnb-typescript-prettier',
'plugin:import/typescript'
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: path.join(__dirname, './tsconfig.json'),
tsconfigRootDir: './src',
},
settings: {
"import/parsers": { // add this definition
"#typescript-eslint/parser": [".ts", ".tsx"],
},
'import/resolver': {
alias: {
map: [
// define each alias here
['components', path.join(__dirname, './src/components')],
],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
},
typescript: {
project: path.join(__dirname, './tsconfig.json'),
},
},
},
}
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287
if vite-tsconfig-paths is not working for you. Make sure you didn't install v4.0.0. That version has a bug.
v4.0.1 fix it.
Install with the following:
npm install vite-tsconfig-paths#latest
Should install v4.0.1 at least.
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287

eslint + jsconfig + nextjs module path aliases (absolue path import - #)

I am trying to import the files using custom aliases following the nextjs documentation.
My current approach is
from
import Header from '../../../components/Header';
to
import Header from '#components/Header';
I am getting the expected result. But eslint throws the following error:
unable to resolve path to module (eslint - import/no unresolved)
And I have tried adding the following line in my eslintrc file to resolve the error
settings: {
'import/resolver': {
node: {
paths: ['src'],
},
},
},
But still the eslint throws the same error.
What is the correct approach to resolve this one?
Thanks in advance...
Note: I don't want to remove eslint and I need #components import aliases
Finally after digging into lots of GitHub answers and etc...
Inside your eslintrc file... add the following aliases
settings: {
'import/resolver': {
alias: {
map: [
['#components', '../../../components/'],
['#images', '../../../assets/images/'],
],
extensions: ['.js', '.jsx'],
},
},
},
and also to fix flow error
inside your flowconfig file add the name_mapper
module.name_mapper='^#components' ->'<PROJECT_ROOT>/../../../components'
module.name_mapper='^#images' ->'<PROJECT_ROOT>/../../../assets/images'
You need to also install npm i -D eslint-import-resolver-typescript and then add below to eslint config file:
"settings": {
"import/resolver": {
"typescript": {} // this loads <rootdir>/tsconfig.json to eslint
},
}
Reference: https://gourav.io/blog/nextjs-cheatsheet
You can try adding your custom paths in tsconfig.json/jsconfig.json, like so:
Add a baseUrl in your compilerOptions (in my case it's "baseUrl": ".")
Add your paths in a paths object:
"paths": {
"components": ["components/*"],
}

Integrating antd with react-boilerplate

I added this to the production config:
babelQuery: {
plugins: [["import", { libraryName: "antd", style: true }]],
},
but I'm still getting errors like ReferenceError: Menu is not defined. Am I missing something? Everything works fine locally when I add the same to the dev config so I'm a little confused.
I'm currently having the exact same problem. So I'll add the extra info here.
I too the information from the following page to setup the ant-design kit:
https://ant.design/docs/react/use-with-create-react-app
The webpack.dev.babel contains the following babelQuery and is working fine:
babelQuery: {
presets: ['babel-preset-react-hmre'].map(require.resolve),
plugins: [['import', { libraryName: 'antd', style: true }]],
},
The development environment runs fine.
But, when adding the same plugins configuration to the webpack.prod.babel like this:
babelQuery: {
plugins: [['import', { libraryName: 'antd', style: true }]],
},
I'm getting the error like #userinev when loading the page after running the production build.
Uncaught ReferenceError: Menu is not defined
It's having issues with loading the first component that gets loaded from the antd library.
When removing the plugins configuration from the prod-config, the app is loading, but the styling is missing.
UPDATE:
The dot (.) in Menu.Item is the problem in the production-build.
The workaround is to create an 'alias', like
const Item = Menu.Item;
See: https://github.com/ant-design/ant-design/issues/5060#issuecomment-283339199
Alternatively, you can remove the boilerplate's including on package.json of the babel plugin that causes error:
Delete this:
"plugins": [
"transform-react-inline-elements"
]

Error when trying babelify of a react application which has another react component as node module

I am trying to setup a react based component library using browserify. This is importing other react based component library as a node module. Following is the browserify configuration in grunt-browserify.
{
options: {
"transform": [
[
"babelify",
{
"presets": [
"es2015",
"react",
"stage-0"
]
}
]
],
browserifyOptions: {
debug: true,
extensions: ['.js', '.jsx'],
entries: ['./src/js/index.js']
}
},
dist: {
src: ['src/index.js'],
dest: 'dist/index.js'
}
}
I am importing a node module which contains react component.
import orb from 'orb';
import React from 'react';
class ReactComponent extends React.Component {
componentDidMount() {
this.ptable = new orb.pgridwidget(this.props.config);
this.ptable.render(ReactDom.findDOMNode(this));
}
render() {
return (<div></div>);
}
}
export ReactComponent;
I am getting following error.
SyntaxError: Unexpected token (102:12) while parsing //node_modules/orb/src/js/react/orb.react.PivotChart.jsx while parsing file: //node_modules/orb/src/js/react/orb.react.PivotChart.jsx
Token position being mentioned is basically jsx. Looks like babelify is not using preset react for node_modules. How to make browserify use babel presets react for this file?
Update
While working on webpack I have faced similar issue which I was able to resolve later. But looks like browserify don't accept additional files like webpack does. Tried options like noParse, external but those are not working.
Able to resolve the issue by adding node module main file to entries object. This is not clearly mentioned in definition for entries in config object.
browserifyOptions: {
debug: true,
extensions: ['.js', '.jsx'],
entries: ['node_modules/orb/src/orb.js', './src/js/index.js']
}
Added a new entry in browserifyOptions

How to set up Babel 6 stage 0 with React and Webpack

My understanding from the docs
I see that Babel 6 has three presets for now: es2015, react and stage-x.
I read that I can set those in .babelrc like so:
{
"presets": ["es2015", "react", "stage-0"]
}
or directly in package.JSON like so:
{
...,
"version": x.x.x,
"babel": {
"presets": ["es2015", "react", "stage-0"]
},
...,
}
I can further use babel-loader with webpack like this:
loader: 'babel?presets[]=es2015'
My problem
So to compile everything nice and clean I'm adding babel-loader, which has just been updated to work with Babel6, to the webpack config like this:
module.exports = function(options) {
var jsLoaders = ['babel?presets[]=es2015'];
[...]
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: jsLoaders
},
{
test: /\.jsx$/,
exclude: /node_modules/,
loaders: options.production ? jsLoaders : ['react-hot'].concat(jsLoaders)
},
[...]
Now when I compile without .babelrc in root or presets options set in package.JSON, i.e. only with the babel-loader es2015 preset set in the webpack config I get an unexpected token error about static propTypes in my React component class:
ERROR in ./app/components/form/index.jsx
Module build failed: SyntaxError: /Library/WebServer/Documents/yarsk.test/app/components/form/index.jsx: Unexpected token (19:19)
17 | // ES6 React Component:
18 | export default class SurveyForm extends Component {
> 19 | static propTypes = {
| ^
On GitHub I got told this is a stage-1 feature, namely transform-class-properties. So I would like to implement stage-0 right away.
BUT
When I do so by adding .babelrc or defining package.JSON like above I get a very weird build fail error:
ERROR in ./app/components/form/index.jsx
Module build failed: Error: /Library/WebServer/Documents/yarsk.test/app/components/form/index.jsx: We don't know what to do with this node type. We were previously a Statement but we can't fit in here?
at NodePath.insertAfter (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/modification.js:181:13)
at NodePath.replaceWithMultiple (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/replacement.js:92:8)
at handleClassWithSuper (/Library/WebServer/Documents/yarsk.test/node_modules/babel-plugin-transform-class-constructor-call/lib/index.js:80:10)
at PluginPass.Class (/Library/WebServer/Documents/yarsk.test/node_modules/babel-plugin-transform-class-constructor-call/lib/index.js:101:11)
at newFn (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/visitors.js:233:27)
at NodePath._call (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/context.js:72:18)
at NodePath.call (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/context.js:44:17)
at NodePath.visit (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/context.js:102:12)
at TraversalContext.visitQueue (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:151:16)
at TraversalContext.visitSingle (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:111:19)
at TraversalContext.visit (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:195:19)
at Function.traverse.node (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/index.js:139:17)
at NodePath.visit (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/path/context.js:106:22)
at TraversalContext.visitQueue (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:151:16)
at TraversalContext.visitMultiple (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:106:17)
at TraversalContext.visit (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/context.js:193:19)
at Function.traverse.node (/Library/WebServer/Documents/yarsk.test/node_modules/babel-traverse/lib/index.js:139:17)
# ./app/index.jsx 9:0-28
Or in short: Module build failed: Error: /.../index.jsx: We don't know what to do with this node type. We were previously a Statement but we can't fit in here?
This is where I'm stuck. I wrote this component with Babel5 when I was able to compile with babel-loader like this and everything worked fine:
loader: 'babel?optional[]=runtime&stage=0
Now I'm getting the mentioned errors compiling.
Is this a babel-loader issue, or a babel issue?
Where do I have to configure stage-0 so that it won't
throw errors?
Update
When compiling with presets set and using the mentioned workaround for the class export bug (must not export class until after creating it) the order of the set presets changes the error message. When I set stage-0 first the error now is 'this' is not allowed before super() (This is an error on an internal node. Probably an internal error)
When I put stage-0 second or third I get the message about syntax error from above.
Latest
For the latest advances regarding these bugs see my post or the new babel issue tracker on phabricator for more. (Basically compiling is fixed as of 6.2.1 but there's other things happening now)
All the bugs mentioned in this article are completely fixed as of Babel 6.3.x. Please update your dependencies if you're still having issues.
The two pretty heavy bugs I ran into here, namely the direct export of an ES6 class with a static property and a problem with the ES6 constructor are discussed in the answers of this thread and can be found on GitHub explicitly here (export bug) and here (constructor bug). (GitHub Issue Tracker has been closed and issues, bugs and requests have moved here.)
These are both officially confirmed bugs, fixed since Babel 6.3.17
(Maybe one or two earlier, not before 6.3.x, this is the version I'm on and everything is working as it was with Babel5. Happy coding everyone.)
(For the records:)
So if you get the following error message in the CLI:
We don't know what to do with this node type. We were previously a Statement but we can't fit in here?
Chances are you are exporting an ES6 class with a static property like this or in a similar manner (note that this doesn't seem to be connected to the class being extended anymore but rather to a class having a static property):
import React, { Component, PropTypes } from 'react'
export default class ClassName extends Component {
static propTypes = {...}
// This will not get compiled correctly for now, as of Babel 6.1.4
}
The simple workaround as mentioned by Stryzhevskyi and several people on GitHub:
import React, { Component, PropTypes } from 'react'
class ClassName extends Component {
static propTypes = {...}
}
export default ClassName // Just export the class after creating it
The second issue is about the following error:
'this' is not allowed before super() (This is an error on an internal node. Probably an internal error)
Despite being a legit rule as pointed out by Dominic Tobias this is a confirmed bug where it appears that extended classes having their own properties will throw this or a similar message. As for now I have not seen any workarounds for this one. Lots of people rolled back to Babel5 for this reason for now (as of 6.1.4).
Supposedly this was fixed with the release of Babel 6.1.18 (see above GitHub issue) but people, me included, still see the same exact problem happening.
Also take note that for now the order in which you load the babel presets stage-x, react and es2015 seems to be important and may change your output.
As of Babel 6.2.1
both of these bugs are fixed, code compiles fine. But... there is still another one that probably affects a lot of people working with react, that throws ReferenceError: this hasn't been initialised - super() hasn't been called at runtime. Referenced here. Stay tuned...
Completely fixed since Babel 6.3.17
(Maybe one or two earlier, not before 6.3.x, this is the version I'm on and everything is working as it was with Babel5. Happy coding everyone.)
Try to replace your export with such construction:
class SurveyForm extends Component {/*implementation*/}
export default SurveyForm
Here is a working example with Babel 6, React, Webpack and Sequelize:
https://github.com/BerndWessels/react-webpack
Basically this is the .babelrc
{
"presets": [
"es2015",
"react",
"stage-0"
],
"env": {
"development": {
"plugins": [
"babel-relay-plugin-loader",
[
"react-transform",
{
"transforms": [
{
"transform": "react-transform-hmr",
"imports": [
"react"
],
"locals": [
"module"
]
},
{
"transform": "react-transform-catch-errors",
"imports": [
"react",
"redbox-react"
]
}
]
}
]
]
},
"production": {
"plugins": [
"babel-relay-plugin-loader"
]
}
}
}
and these are the module versions
babel-core#6.3.17
babel-loader#6.2.0
babel-plugin-react-transform#2.0.0-beta1
babel-preset-es2015#6.3.13
babel-preset-react#6.3.13
babel-preset-stage-0#6.3.13
That works for me.
After having the same issues, I was able to get this working with React using the below WebPack config.
module.exports = {
entry: './app/Index.js',
output: { path: __dirname, filename: 'dist/bundle.js' },
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['react']
}
}
]
}
};
I also needed to install babel-preset-react too.
npm install --save-dev babel-preset-react
EDIT: Of course you might still need to also include the ES2015 preset if you are writing ES6 as well.
Babel Presets can be found here: https://github.com/babel/babel/tree/development/packages
Have you tried?:
presets: [{
plugins: [
'transform-class-properties'
]
}, 'stage-0', 'es2015', 'react']
Have you tried using just stage-1?
Using query property worked for me.
```
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-1', 'react']
}
}]
}
```
Of course, I haven't been able to use .babelrc and babel options in package.json. Still trying to figure out babel-*v6.0

Resources