react-three/postprocessing. Module parse failed - javascript

As soon as import Effect Composer into an active document, I get this error message. Could there be a possibility of my model/material causing this?? I am not even using the Effect Composer in Script. Or could it be that I need some kind of background??
*./node_modules/screen-space-reflections/dist/index.js 675:33
Module parse failed: Unexpected token (675:33)
You may need an appropriate loader to handle this file type.
| var boneMatrices = material[boneMatricesName];
|
if (material[boneMatricesName]?.length !== skeleton.boneMatrices.length) {
| delete material[boneMatricesName];
| boneMatrices = new Float32Array(skeleton.boneMatrices.length);*
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import './styles.css'
import { EffectComposer } from '#react-three/postprocessing'
//I just inserted it here to see if this causes the failure and it does
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);

Have you tried to install the es2015 preset??
REF: "You may need an appropriate loader to handle this file type" with Webpack and Babel
npm install babel-preset-es2015
You need to install the es2015 preset:
npm install babel-preset-es2015
and then configure babel-loader:
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
Maybe you need to add the file-loader under your modules.
https://www.npmjs.com/package/file-loader
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
],
},
};

Related

webpack can't parse material ui button in a child component

I'm trying to bundle some React components with webpack.
But when I launch webpack --mode=development, i get this error :
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const OwnButton = () => {
| return ( <Button color='secondary' variant='outlined'
This is my webpack config :
const path = require('path');
module.exports = {
entry: './src/app.js', // relative path
output: {
path: path.join(__dirname, 'public'), // absolute path
filename: 'js/bundle.js' // file name
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
This is my app.js config :
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Button from '#material-ui/core/Button';
import OwnButton from './Components/OwnButton';
const template = <Button>Hello from react jsx</Button>;
ReactDOM.render(template, document.getElementById('root'));
ReactDOM.render(<OwnButton/>, document.getElementById('React-OwnButton'));
And the wanted component (index.jsx) :
import Button from '#material-ui/core/Button';
const OwnButton = () => {
return (
<Button color='secondary' variant='outlined'>
Hello from my own component
</Button>
);
};
export default OwnButton;
And my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
I don't understand how the call l.6 on app.js can work but not the on index.jsx l.6.
Where must I put the loader for this, in babel?
The problem is that you configured the Babel Loader to only intervene for .js files.
Try changing: test: /\.js$/ -> test: /\.((js)|(jsx))$/
This will make the loader work for .jsx files too.

Webpack packaging ReactDOM causing loader error

When I run webpack --mode development, I get the following error:
Edit
A comment requested to see my .babelrc, added below
- I've tried all combinations of index and app files as both, or each, as .jsx files, but to no avail.
- I've also tried removing and readding all the node modules as latest version for node (v10.x.x)
ERROR in ./src/index.js 4:16
Module parse failed: Unexpected token (4:16)
You may need an appropriate loader to handle this file type.
| import ReactDOM from "react-dom";
| import app from "./app.js";
ReactDOM.render(<app />, document.getElementById("root"));
app.js
import React, {Component} from "react";
import {hot} from "react-hot-loader";
import "./app.css";
class app extends Component{
render(){
return(
<div className="app">
<h1> Hello, World! </h1>
</div>
);
}
}
export default app;
index.js
import React from "react";
import ReactDOM from "react-dom";
import app from "./app.js";
ReactDOM.render(<app />, document.getElementById("root"));
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.jsx",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /css\*\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://testsite.test/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
{
"presets": [
"env",
"react",
"stage-0"
],
"plugins": [
"transform-class-properties",
"transform-decorators",
"transform-react-constant-elements",
"transform-react-inline-elements"
]
}
I'm going to try and get this loaded on GH soon, but I'm having some real trouble with my GH account and connection on my device right now (ssh key issues). Bear with me on that, hopefully the above is enough to help.
Edit #2: Here is my github repo
https://github.com/johnfwebdev/testsite.test
transform react jsx with babel like this, give it a try
.babelrc
{
"presets": [["#babel/preset-env"]],
"plugins": [
"#babel/plugin-transform-react-jsx"
]
}
I figured it out everyone.... :facepalm:
webpack-config.js should have been named webpack.config.js

“You may need an appropriate loader to handle this file type” with Webpack and Babel

I'm upgrading from an arcane version of webpack to webpack 2 and I'm getting an error:
ERROR in ./scripts/app.js
Module parse failed: /Users/zackshapiro/dev/glimpse-electron/node_modules/eslint-loader/index.js!/Users/zackshapiro/dev/glimpse-electron/scripts/app.js Unexpected token (32:4)
You may need an appropriate loader to handle this file type.
|
| render((
| <Provider store={store}>
| <Home />
| </Provider>
# multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./scripts/app.js
My webpack.config.js looks like this:
const webpack = require('webpack');
const path = require('path');
console.log(path.resolve(__dirname, 'public/built'));
console.log("we here");
module.exports = {
entry: {
app: ['webpack/hot/dev-server', './scripts/app.js']
},
output: {
// path: './public/built',
path: path.resolve(__dirname, 'public/built'),
filename: 'bundle.js',
publicPath: 'http://localhost:8080/built/'
},
devServer: {
contentBase: './public',
publicPath: 'http://localhost:8080/built/'
},
module: {
rules: [
{
test: /\.jsx?$/,
enforce: "pre",
loader: "eslint-loader",
exclude: /node_modules/
},
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015', 'stage-3']
}
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
{ test: /\.(ttf|eot|otf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$")),
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnWarning: false,
failOnError: true
}
}
})
]
}
And my app.js looks like this:
require('../styles/main.scss');
require('../styles/menubar.scss');
require('../styles/panel.scss');
require('../styles/sky.scss');
require('../styles/dock.scss');
require('../styles/sector.scss');
require('../styles/slot.scss');
require('../styles/element_builder.scss');
'use strict';
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {compose, createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import reducer from './entities/reducers';
import sagas from './entities/sagas';
import Home from './containers/home';
const sagaMiddleware = createSagaMiddleware();
const composedCreateStore = compose(applyMiddleware(sagaMiddleware))(createStore);
const store = composedCreateStore(reducer, {});
sagaMiddleware.run(sagas);
render((
<Provider store={store}>
<Home />
</Provider>
), document.getElementById('content'));
I don't have a .babelrc file in my root directory because I have that object in my loaders in webpack.config.js
Any suggestions on how to fix this would be very welcome. Thanks!
module.rules replaces module.loaders in Webpack 2, so it's possible that by providing both Webpack isn't using module.loaders (which is there for backwards-compatibility) at all - try moving the rules you currently have in module.loaders into module.rules instead.
Edit: peeking inside the current version of Webpack's NormalModuleFactory, this is what it's doing:
this.ruleSet = new RuleSet(options.rules || options.loaders);

jQuery needed for Bootstrap in React project

I am developing a React.js project where instead of using React-Bootstrap, I am loading the CSS of Bootstrap into my project. I am now needing to import the jQuery so that I can use dropdown menus etc.
Entry point file (index.js) - in the hope it would work
'use strict'
import React from 'react'
import { Route, Router, IndexRoute, browserHistory } from 'react-router'
import { render } from 'react-dom'
// Pages
import Main from './pages/main/main'
import Home from './pages/home/home'
import About from './pages/about/about'
window.jQuery = window.$ = require('jquery/dist/jquery.min')
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import '../node_modules/bootstrap/dist/js/bootstrap.min.js'
render((
<Router history={browserHistory}>
<Route name='home' path='/' component={Main}>
<IndexRoute component={Home} />
<Route name='about' path='about' component={About} />
</Route>
</Router>), document.getElementById('app'))
Webpack file
'use strict'
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: [
'./browser/index'
],
output: {
path: path.join(__dirname, 'public', 'js'),
filename: 'bundle.js',
publicPath: '/public/js/'
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{ test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [ 'es2015', 'react' ]
},
include: path.join(__dirname, 'browser')
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{ test: require.resolve('jquery'), loader: 'imports?jQuery=jquery' }
]
}
}
The error appears in Chrome Dev tools: 'Bootstrap's Javascript requires jQuery'. I'm wondering whether perhaps I am missing something in terms on loaders in the webpack file, or need an import statement in the entry file?
Please make sure you have installed 'imports-loader', (npm install --save imports-loader). And in module.exports try this:
{ test: /bootstrap.+\.(jsx|js)$/, loader: 'imports?jQuery=jquery,$=jquery,this=>window' }
The really nice post regarding it I've found here: http://reactkungfu.com/2015/10/integrating-jquery-chosen-with-webpack-using-imports-loader/
Unfortunately provided solution doesn't work for me. In the case above Bootstrap and jQuery are both installed as npm dependencies under node_modules directory? I'm using WebPack 2, so I have converted the loader element as follows:
{
test: /bootstrap.+\.(jsx|js)$/,
use: 'imports-loader?jQuery=jquery,$=jquery,this=>window',
exclude: /node_modules/
}

Test Coverage React, Istanbul -_registerComponent(...): Target container is not a DOM element

I am writing an app with react / redux / webpack. I am building out my testing with karma, mocha and want to use istanbul for test coverage. In an attempt to get coverage to work with karma-coverage I have set up the following karma.config.js
var argv = require('yargs').argv;
var path = require('path');
var webpack = require('webpack');
const PATHS = {
test: path.join(__dirname, 'test'),
app: path.join(__dirname, 'app'),
}
module.exports = function(config) {
config.set({
// only use PhantomJS for our 'test' browser
browsers: ['PhantomJS'],
// just run once by default unless --watch flag is passed
singleRun: !argv.watch,
// which karma frameworks do we want integrated
frameworks: ['mocha', 'chai'],
// include some polyfills for babel and phantomjs
files: [
'node_modules/babel-polyfill/dist/polyfill.js',
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
// './test/**/*.js', // specify files to watch for tests,
'test/index.js',
],
preprocessors: {
// these files we want to be precompiled with webpack
// also run tests through sourcemap for easier debugging
// 'test/*.spec.js': ['webpack'],
'test/index.js': ['webpack', 'sourcemap']
},
// A lot of people will reuse the same webpack config that they use
// in development for karma but remove any production plugins like UglifyJS etc.
// I chose to just re-write the config so readers can see what it needs to have
webpack: {
devtool: 'inline-source-map',
resolve: {
// allow us to import components in tests like:
// import Example from 'components/Example';
root: PATHS.app,
// allow us to avoid including extension name
extensions: ['', '.js', '.jsx'],
// required for enzyme to work properly
alias: {
'sinon': 'sinon/pkg/sinon'
}
},
module: {
// don't run babel-loader through the sinon module
noParse: [
/node_modules\/sinon\//
],
preLoaders: [
// instrument only testing sources with Istanbul
// {
// test: /\.js$/,
// include: path.resolve('app/'),
// exclude: /node_modules/,
// loader: 'istanbul-instrumenter'
// }
{
test: /\.jsx?$/,
exclude: [/node_modules/, /test/],
loader: 'isparta-instrumenter-loader'
},
],
// run babel loader for our tests
loaders: [
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', 'survivejs-kanban']
}
},
],
},
// required for enzyme to work properly
externals: {
'jsdom': 'window',
'cheerio': 'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': 'window'
},
},
// displays tests in a nice readable format
reporters: ['spec', 'coverage'],
webpackMiddleware: {
noInfo: true
},
// tell karma all the plugins we're going to be using to prevent warnings
plugins: [
'karma-mocha',
'karma-chai',
'karma-webpack',
'karma-phantomjs-launcher',
'karma-spec-reporter',
'karma-sourcemap-loader',
'karma-coverage'
]
});
};
karma's entry point is just test/index.js. Which looks like this
// require all the tests so they will run.
const testsContext = require.context('.', true, /spec/);
testsContext.keys().forEach(testsContext);
// require all the .js and .jsx files in app so they will be included in coverage
const componentsContext = require.context('../app/', true, /jsx?$/);
// Date: April 16 2016
// Author: Benjamin Conant
// componentsContext.keys() is an array that includes file paths for all the
// .js and .jsx files in ./app .... karma fails with
// PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
// Invariant Violation: _registerComponent(...): Target container is not a DOM element.
// at /Users/benconant/Dev/MyFin/my-fin-front-end/test/index.js:15283 <- webpack:///~/react/~/fbjs/lib/invariant.js:45:0
// if the entry point index.jsx file is included. Seems to have somthing
// to do with trying to actually write to the DOM. So, I filter out index.jsx and the tests run very well.
// This means that we will probubly not be able to test index.jsx until this is solved.
let componentsContextKeysWithoutIndexJsx = componentsContext.keys().filter(function (filePath) { return filePath !== './index.jsx' });
componentsContextKeysWithoutIndexJsx.forEach(componentsContext);
// componentsContext.keys().forEach(componentsContext); --- the way it should be if we did not have to remove ./index.jsx
As you can see from the dated comment. If index.jsx is included, when I run the tests I get ...
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
Invariant Violation: _registerComponent(...): Target container is not a DOM element.
at /Users/benconant/Dev/MyFin/my-fin-front-end/test/index.js:15283 <- webpack:///~/react/~/fbjs/lib/invariant.js:45:0
here is my index.jsx for reference
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';;
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { Router, Route, Link, browserHistory, hashHistory, IndexRoute } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import configureStore from './store/configureStore';
import todoApp from './reducers';
import App from './containers/app/App';
import IntroSlides from './containers/IntroSlides';
import LandingPage from './containers/LandingPage';
let store = configureStore();
const history = process.env.HASH_ROUTING ? syncHistoryWithStore(hashHistory, store) : syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={LandingPage} />
<Route path="intro" component={IntroSlides}/>
</Route>
</Router>
</Provider>,
document.getElementById('app')
)
I am about one week into the react ecosystem and so am almost certainly doing something silly but this has taken up many hours and help would greatly appreciated!
I had that same problem, which in my case occurred because React couldn't find the element in which it needed to render the html.
I found a quick fix by adding the following if statement into my main js file:
if ($('#app').length <= 0) {
$('body').prepend('<div id="app"></div>');
}
ReactDom.render(
<App />,
document.getElementById('app')
);
I'm aware this must not be the best way of fixing it, but at least it works for now. If anyone knows of a better way, please let us know!
I've also posted this solution on the thread you mentioned in your comment.

Categories

Resources