React - Module parse failed - parsing

I've got this error all day when running webpack from command line:
ERROR in ./index.js
Module parse failed: /home/kuro/Workspace/ExpressJS/corate/src/index.js Line 10: Unexpected token <
You may need an appropriate loader to handle this file type.
| render:function(){
| return (
| <div>
| <div className="left">
| <img src={mac}/>
Here is my code in index.js
var React=require('react');
var ReactDOM=require('react-dom');
var style=require('../public/css/style.css');
var mac=require('../public/images/img_landing_page_mac.png');
var chrome=require('../public/images/btn_get_chrome.png');
var Content=React.createClass({
render:function(){
return (
<div>
<div className="left">
<img src={mac}/>
</div>
<div className="right">
<h2 style={font-size: '33px', letter-spacing: '5px'}>
Organize <br>Modern Knowledge<br> for Mankind
</h2>
<p style={font-size: '20px', margin-top: '35px', letter-spacing: '4px'}>
Consume, Colect and Revisit <br>Knowledge at Your Fingertips
</p>
<a href="#" style={margin-top: '80px', display: 'inline-block', margin-left: '-17px'}>
<img src={chrome}/>
</a>
</div>
</div>
);
}
});
ReactDOM.render(<Content/>,document.getElementByClassName('container'));
And configuration in webpack.config.js:
module.exports={
context: __dirname+'/src',
entry:'./index.js',
output:{
path:__dirname+'/static',
filename:'bundle.js'
},
module:{
loaders:[
{
test:/\.png$/,
loader:'url?limit=10000'
},
{
test:/\.jpg$/,
loader:'url?limit=10000'
},
{
test:/\.css$/,
loader:'style!css'
}
]
}
}
I couldn't figure out what is wrong with it. Am I missing something here?

You need add babel-loader, with react preset, do the following steps
npm i --save-dev babel-loader babel-preset-react babel-preset-es2015
add to webpack.config.js configs for babel-loader ( to loaders: [..] section)
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
Update: babel-preset-es2015, babel-preset-react was deprecated in favor of using #babel/env and #babel/preset-react
npm i --save-dev babel-loader #babel/core #babel/preset-react #babel/preset-env
add to webpack.config.js configs for babel-loader
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
}
]

well mate . this worked
module: {
rules: [
// CSS loader here
{
test: /\.svg$/,
use: 'file-loader'
}
]
}
add this to your webpack config files
npm install --save-dev style-loader css-loader

Related

React Website gives blank page on IOS Safari

I created a single page website with React. While it works fine on Android and Windows devices, I get a white page error on IOS-based devices. I have tried many solutions.
I don't get console error for Safari (latest version) for Windows either.
Here for live : https://fitbodyclub.netlify.app/
It has many code you may look at it here : https://github.com/kececibora/FitBodyClub-Website
index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
package.json:
{
"name": "fitclub",
"homepage": "https://fitbodyclub.netlify.app/",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"framer-motion": "^6.3.15",
"number-counter": "^1.0.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-onclickoutside": "^6.12.2",
"react-scripts": "5.0.1",
"react-scroll": "^1.8.7",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I tried :
1 - "start_url": ".", // in manifest.json
2 - delete iframe from files
3- "homepage": ".", // added to package.json
4- "start_url": "``https://fitbodyclub.netlify.app/``", // added in manifest.json
5-"start": "yarn run start:tw & sleep 1 && yarn run start:cra", // added in package.json
6- <iframe allow="fullscreen" // added allow to iframe
7-
I started to rebuild it. I found the file gives that problem :
// import Header from "./Header/Header";
import "./Hero.css";
import hero_image from "../assets/hero_image.png";
import hero_image_back from "../assets/hero_image_back.png";
import Heart from "../assets/heart.png";
import Calories from "../assets/calories.png";
const transition = { type: "spring", duration: 3 };
const mobile = window.innerWidth <= 768 ? true : false;
function Hero() {
return (
<div className="hero" id="home">
<div className="blur hero-blur"></div>
<div className="left-h">
{/* <Header /> */}
{/* slogan */}
<div className="slogan">
<div
initial={{ left: mobile ? "165px" : "238px" }}
whileInView={{ left: "8px" }}
transition={{ ...transition, type: "tween" }}
></div>
<span>Sporun Kalbi burada atıyor 💛💛</span>
</div>
{/* Büyük Slogan */}
<div className="hero-text">
<div>
<span className="bosluk-text">Hayalinizdeki </span>
<span>Vücuda</span>
</div>
<div>
<span>Kavuşma Zamanı</span>
</div>
<div>
<span>
Burada sizlere hayalinizdeki vücuda kavuşmanıza yardım ediyoruz.
Sen de yapabilirsin!
</span>
</div>
</div>
{/* Figürler */}
<div className="figures">
<div>
<span>+500</span>
<span>metrekare</span>
</div>
<div>
<span>+2500</span>
<span>Üyelik</span>
</div>
<div>
<span>+250</span>
<span>Ekipman</span>
</div>
</div>
{/*Butonlar */}
<div className="hero-buttons">
<button className="btn">Katıl Bize</button>
<button className="btn">Daha Fazlası</button>
</div>
</div>
<div className="right-h">
<button className="btn">Üye Girişi</button>
<div
initial={{ right: "-1rem" }}
whileInView={{ right: "4rem" }}
transition={transition}
className="heart-rate"
>
<img src={Heart} alt="" />
<span>Heart Rate</span>
<span>116bpm</span>
</div>
{/* Hero images */}
<img src={hero_image} alt="" className="hero-image" id="hero_image" />
<img
initial={{ right: "11rem" }}
whileInView={{ right: "20rem" }}
transition={transition}
src={hero_image_back}
alt=""
className="hero-image-back"
id="hero_image_back"
/>
{/* Kalori */}
<div
initial={{ right: "37rem" }}
whileInView={{ right: "28rem" }}
transition={transition}
className="calories"
>
<img src={Calories} alt="" />
<div>
<span>Kalori</span>
<span>220 kcal</span>
</div>
</div>
</div>
</div>
);
}
export default Hero;
I started to rebuild it. I found the file gives that problem :
Part by part i builded so, a css element mix-blend-mode causes problem.
.App{mix-blend-mode: overlay;}

"export 'default' (imported as 'Vue') was not found in 'vue' error in ruby on rails and vue integration. established setup by webpacker: install:vue

the below code is hello_vue.js file
import Vue from 'vue'
import App from '../app.vue'
document.addEventListener('DOMContentLoaded', () => {
const app = new Vue({
render: h => h(App)
}).$mount()
document.body.appendChild(app.$el)
console.log(app)
})
this is app.vue
<template>
<div id="app">
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data: function () {
return {
message: "Hello Vue!"
}
}
}
</script>
<style scoped>
p {
font-size: 2em;
text-align: center;
}
</style>
and added below comment in root view page
<%= javascript_pack_tag 'hello_vue.js' %>
When you run the command rails webpacker:install:vue will try to install the latest version of Vue which is v3, but the autogenerated syntax for the hello_vue.js file comes from an older version of Vue v2 which is unsupported. Modify the hello_vue.js with this:
import { createApp } from "vue";
import App from "../app.vue";
document.addEventListener("DOMContentLoaded", () => {
const app = createApp(App);
app.mount("#app");
});
And also the rails command forget to add a devDependency to package.json to support this new Vue v3 syntax.
yarn add --dev #vue/compiler-sfc

Uncaught TypeError: $(...).sortable is not a function in Rails 6

Strugle alot but couldn't solve this problem. It been nightmare for me. I am using rails 6. and jquery ui "jquery-ui": "^1.13.0". I have added gem gem 'acts_as_list' and added yarn as yarn add jquery-ui.
I have added in application.js file
`require("jquery-ui/ui/widget")
require("jquery-ui/ui/widgets/sortable")`
and added the code
$(document).on("turbolinks:load", () => {
$("#employeeLevel").sortable({
handle: '.handle',
update: function(e, ui) {
Rails.ajax({
url: $(this).data("url"),
type: "PATCH",
data: $(this).sortable('serialize'),
success: function(result){
console.log('my msg'+result);
}
});
}
});
})
In index.html.slim addded an id as
tbody id="employeeLevel" data-url="<%= sort_employee_levels_path %>"
Waiting for your response. Thank you in advance
This is what I require for sortable:
import 'jquery'
import 'jquery-ui/themes/base/core.css'
import 'jquery-ui/themes/base/theme.css'
import 'jquery-ui/ui/widgets/sortable'
import 'jquery-ui/themes/base/sortable.css'
You may need to expose jQuery in config/webpack/environment.js:
// Expose jQuery to scripts external to webpack
environment.loaders.append('expose', {
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {
exposes: ['$', 'jQuery']
}
})

Angular component not executing with Webpack

Short Version:
I'm building an app with Angular2 and Webpack. I have the bundles building successfully, but when I include them on my page, the angular components loading. No errors are showing up.
webpack.config.js
"use strict";
let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let helpers = require('./webpack.helpers.js');
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'app': helpers.root('/Modules/Shared/Main.ts'),
'vendor': helpers.root('/External/Vendor.ts'),
'polyfills': helpers.root('/External/Polyfill.ts')
},
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
},
output: {
path: helpers.root('/wwwroot/scripts'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{ loader: 'awesome-typescript-loader', options: { tsConfig: 'tsconfig.json' } },
'angular-router-loader',
'angular2-template-loader',
'source-map-loader',
'tslint-loader'
]
},
{
test: /\.(png|jpg|gif|woff|woff2|ttf|svg|eot)$/,
loader: 'file-loader?name=assets/[name]-[hash:6].[ext]'
},
{
test: /favicon.ico$/,
loader: 'file-loader?name=/[name].[ext]'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
})
},
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.html$/,
loader: 'raw-loader'
}
]
},
plugins: [
new ExtractTextPlugin('css/[name].bundle.css'),
new webpack.NoEmitOnErrorsPlugin(),
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
'Modules/', // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
}),
new HtmlWebpackPlugin()
]
};
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"removeComments": true,
"skipLibCheck": true,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules",
"wwwroot"
],
"compileOnSave": true
}
The files are being generated correctly:
http://imgur.com/a/xzw0E
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"]</title>
<base href="/" />
</head>
<body style="background-color: #333;">
#RenderBody()
<script type="text/javascript" src="/scripts/polyfills.js"></script>
<script type="text/javascript" src="/scripts/vendor.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
index.cshtml
#using System.Threading.Tasks
#{
ViewData["Title"] = "Home Page";
}
<div style="height: 100%;">
<app-component>Loading...</app-component>
</div>
#section Scripts{
<script type="text/javascript" src="/scripts/app.js"></script>
}
The component I'm expecting to see looks like this:
import { Component } from '#angular/core';
#Component({
selector: 'app-component'
})
export class AppComponent {
constructor() {
console.log('I\'m running !!!!');
}
}
But when I generate the page, it looks like this:
http://imgur.com/a/YrPJf
with no errors in the console:
http://imgur.com/a/Xepl2
Any help is greatly appreciated
Seems you forgot about bootstrapping your application via
platformBrowserDynamic().bootstrapModule(AppModule);

How can I use the Vue.js code from a webpack bundle in a Razor page?

Here is my Razor page code:
#using System.Web.Optimization;
#{ BundleTable.Bundles.Add(
new ScriptBundle("~/Scripts/Vuejs")
.Include("~/Static/Scripts/Vuejs/vue.min.js")); }
#section Scripts {
#Scripts.Render("~/Static/vue/assets/bundle.js")
#Scripts.Render("~/Scripts/Vuejs")
}
<div id="app_container">
{{text}}
</div>
and here is the entry of the webpack javascript:
import Vue from 'vue';
const v = new Vue({
el: '#app_container',
data: { text: 'abcdefg' }
});
Webpack config:
export default {
entry: [
'babel-polyfill',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: 'C:/WebSandbox/Static/vue/assets',
publicPath: '/vue/assets/'
},
devtool: 'source-map',
module: {
loaders: [
{ test: /\.vue$/, loader: 'vue' },
{ test: /\.js/, loader: 'babel', exclude: /node_modules/ },
{ test: /\.json$/, loader: 'json' },
{ test: /\.txt/, loader: 'raw' }
]
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
APP_ENV: JSON.stringify('browser')
}
})
]
};
All the javascript files are in place and when open the page I can see the mapped code from Developer Tools of Chrome. And if I make a break point in the javascript code, it will be hit.
But the text displayed is "{{text}}", not "abcdefg".
If I added following code after the div:
<script>
const v = new Vue({ el: "#app_container", data: { text: "abcdefg" } });
</script>
or add following code and remove the javascript file from #section Scripts part
<script src='~/Static/vue/assets/bundle.js'></script>
It works.
So how can I make my webpack bundle work with the #Scripts.Render in Razor page?
OK, now I found why the bundle not working:
Because the #RenderSection("Scripts", false) was written in the header of _Layout.cshtml. So the bundle JavaScript file will be referenced in the header. But when I switch to the raw reference (script tag), it will be after my div tag where it should be.
When I change the bundle part to:
#section ScriptBlock {
#Scripts.Render("~/Static/vue/assets/bundle.js")
}
It works.
The #RenderSection("ScriptBlock", false) was written in the bottom of the _Layout.cshtml right after the closing tag of body.
I use vuejs with asp.net with browserify rather than webpack.
And the packing should be an independent build step.
I setup a gulp task to take my vue code and bundle it up and place it in the scripts folder of asp.net.
I think you need to do something similar here.

Resources