React code not showing in browser - html

I'm using Webpack to bundle some React code written in JSX format. I have everything up and running as far as compiling goes and it looks as though every thing is correct in the bundle.js output file. When I import it into an HTML file and try to display the React code it doesn't show up for some reason. I've made a regular javascript file and included it in the main.js so that it is also included in the Webpack output file bundle.js and this does show up in the browser. So when the bundle.js is used in my html file I just get the text "Hello, im located in a seperate file" and not the React elements.
React Code(main.js)
require('./extra.js');
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
Regular JS File(extra.js)
document.write("Hello, im located in a seperate file");
Output file after running webpack(bundle.js)
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
React.render(React.createElement(
"h1",
null,
"hello world"
), document.getElementById("app"));
var HelloMessage = React.createClass({
displayName: "HelloMessage",
render: function () {
return React.createElement(
"div",
null,
"Hello ",
this.props.name
);
}
});
ReactDOM.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
/***/ },
/* 1 */
/***/ function(module, exports) {
/**
* Created by sf on 1/14/2016.
*/
document.write("Hello, im located in a seperate file");
/***/ }
/******/ ]);
HTML file im using the script in
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="example"></div>
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>

The examples on the React homepage are not self-sufficient, but rather minimal examples of React itself. Here's how the example you're using might look, starting with index.js:
var React = require( 'react' );
var ReactDOM = require( 'react-dom' );
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
var mountNode = document.getElementById( 'app' );
ReactDOM.render(<HelloMessage name="John" />, mountNode);
And your index.html:
<html>
<body>
<div id="app"></div>
<script src="./build/bundle.js"></script>
</body>
</html>
Notice that it is requiring a script called bundle.js and our source is called index.js. To transform the JSX and package our source into the bundle, we can use Webpack with this basic config:
var webpack = require( 'webpack' );
module.exports = {
context: __dirname + '/src',
entry: './index.js',
devtool: 'source-map',
output: {
path: __dirname + '/build',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loaders: [ 'babel-loader?presets[]=react' ],
}
],
},
};

you either need to put that script tag at the end of the body, or execute the code on document ready. when that script is running in the head, there isnt a div with id = app on the document yet
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>

Related

vue + pure html component?

how to implement vue-cli calling pure html method?
Please check below as sample file. because I have custom pure html code and facing difficulty converting it to vuejs.
product.vue
<template>
<custombutton #childclick="childclick" />
</template>
<script>
export default {
component: { custombutton },
methods: {
childclick(value) {
console.log(value)
}
}
}
</script>
custombutton.html
<html>
<body>
<button #click="childclick" />
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script>
var App = new Vue({
el: '#app',
data() {
return {
vueMessage: 'testing vue message',
}
},
methods: {
childclick() {
this.$emit('childclick', 'success!')
}
},
});
</script>
</html>
Assuming you want to preserve the possibility to call Vue component from both .html file and .vue files, I would recommend moving your Vue logic from custombutton.html file into a separate custombutton.js file, which will export an object representing Vue component previously defined in HTML. You can then import custombutton.js both in custombutton.html and product.vue.
Example:
custombutton.js:
export default {
name: 'CustomButton',
template: '<div>Hello world!</div>'
}
custombutton.html:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script type="module">
import CustomButton from "./custombutton.js"
new Vue({
el: '#app',
components: { CustomButton },
template: '<CustomButton />'
});
</script>
</body>
</html>
product.vue:
<template>
<CustomButton />
</template>
<script>
import CustomButton from "./custombutton.js"
export default {
components: { CustomButton }
}
</script>
Note that:
For custombutton.html to work target browsers should implement ECMAScript modules.
For product.vue to work you should set runtimeCompiler: true in your Vue CLI configuration. (Since the template in custombutton.js is defined as a string runtime compiler needs to be included in the final bundle.)
It is important to find a suitable location for custombutton.js so it can be imported easily using relative paths from both custombutton.html and custombutton.vue files.
Defining the template as a string in custombutton.js can be quite inconvenient, as you have no markup highlighting, however I don't see any workaround for this.
This solution is a bit more cumbersome, but allows template to be written with syntax highlighting into <script> element, which is more convenient than writing template as a string literal into a template property.
custombutton.js:
export default {
name: 'CustomButton',
data: function () {
return { testVar: 125 }
}
}
custombutton.component.html:
The template is now located in #custombutton-template element. "Hello world! 125" should be printed out.
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>
</head>
<body>
<script id="custombutton-template" type="x-template">
<div>Hello world! {{ testVar }}</div>
</script>
<div id="app"></div>
<script type="module">
import CustomButton from "./custombutton.js"
CustomButton.template = "#custombutton-template"
new Vue({
el: '#app',
components: { CustomButton },
template: '<CustomButton />'
});
</script>
</body>
</html>
product.vue: Thanks to Webpack config (see below) we are able to import contents of custombutton.component.html file as a string, parse it and get inner HTML of #custombutton-template element, which is the desired template.
<template>
<CustomButton />
</template>
<script>
import CustomButton from "./custombutton.js"
import CustomButtonComponent from "./custombutton.component.html"
var el = document.createElement("html")
el.innerHTML = CustomButtonComponent
var template = el.querySelector("#custombutton-template").innerHTML
CustomButton.template = template
export default {
components: { CustomButton }
}
</script>
Importing custombutton.component.html file as string is done by non-default Webpack raw-loader, therefore it is necessary to adjust Webpack config:
vue.config.js:
module.exports = {
runtimeCompiler: true,
configureWebpack: {
module: {
rules: [
{
test: /\.component\.html$/,
use: ["raw-loader"]
}
]
}
}
}
package.json:
{
"devDependencies": {
"raw-loader": "^4.0.2"
}
}

how to import HTML file into React component and use it as a component?

I want to import an HTML file into a React component
peft.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
index.js
import perf from perf.html
class Index extends React.Component {
render(){
return (
<iframe src="perf"></iframe> /* like this */
<iframe src="./perf"></iframe> /* or like this */
/* or like any possible way */
);
}
}
export default Index;
so in my case, I need to import a local HTML file and use it in
but I'm getting the error:
Uncaught (in promise) Error: Module parse failed:
C:\Users....\target.html
Unexpected token (1:0) You may need an appropriate loader to handle
this file type.
any ideas?
How to load an HTML file inside of a React Component?
How to add an appropriate loader to handle this file type?
Anything?
I find this solution as most logical:
var __html = require('./template.html');
var template = { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={template} />
);
}
});
but I can not apply it because I'm getting an error:
Uncaught (in promise) Error: Module parse failed: C:\Users\....\target.html Unexpected token (1:0) You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
| <html xmlns="w3.org/1999/xhtml">;
| <head><title>
You can import or require the html file and use it in the src attribute,
var perf =require('./template.html');
class Index extends React.Component {
render(){
return (
<iframe src={perf }></iframe> /* like this */
);
}
}
export default Index;
Spent 2 hours on this.
Two ways to do the same below:
Method1 - iframe (part of page) goes to that html file (chap3.htm)
Method2 - fetch the contents of chap3.htm and set to state, state is added with dangerouslySetInnerHTML
NOTE
Html file is in public directory (myapp\public\chap3.htm).
May work from current directory too, but does not look like as a usual way to load static resource/html from current directory.
Method 1
import React from'react';
import'./App.css';
function App() {
return(
<div className="App">
<iframe src="chap3.htm"></iframe>
</div>
);
}
export default App;
Method 2
import React, { useEffect, useState }from'react';
import'./App.css';
function App() {
let[htmlFileString, setHtmlFileString] = useState();
async function fetchHtml() {
setHtmlFileString(await (await fetch(`chap3.htm`)).text());
}
useEffect(() => {
fetchHtml();
}, []);
return(
<div className="App">
<div dangerouslySetInnerHTML={{ __html: htmlFileString }}></div>
</div>
);
}
export default App;

How to bulid Application template Vue

I'm new to Vue and to ES6
And I did the following:
import Vue from 'vue'
import VueRouter from 'vue-router'
import $ from 'jquery'
Vue.use(VueRouter)
var App = {};
App.template = `
<main-menu></main-menu>
<router-view></router-view>`;
const header = Vue.component('main-menu', require('./components/app/header.vue'));
const facebook = Vue.component('facebook-gif', require('./components/facebook.vue'));
const router = new VueRouter({
routes: [
{
path: '/',
},
{
path: '/facebook',
component: {
facebook: facebook
}
}
]
});
App.app = new Vue({
router,
render (h) {
return h(`div`, App.template)
}
}).$mount('#app');
But what it's nothing render , I just see the main-menu and router-view tags in my broswer...
And when I edit my html and put there this:
<div id="app">
<main-menu></main-menu>
<router-view></router-view>
</div>
I get this error when I'm trying to enter the facebook route:
[Vue warn]: Failed to mount component: template or render function not defined.
and the facebook template is wrapped with template tag and it's inside a vue file
facebook.vue
<template>
<div>
dsfsdsfdsf
<div v-if="showLogin">
<button v-on:click="login">Log In With Facebook</button>
<span v-if="error">{{ error }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showLogin: true,
error:null,
}
},
methods() {
return {
login() {
}
}
}
}
</script>
But the main-menu component is render...
What is the problem?
EDIT
I downloaded the example like wostex said
I create an App.vue file contain:
<template>
<div id="app">
<main-menu></main-menu>
<router-view></router-view>
</div>
</template>
I edit my html file to contain
I added in app.js
import App from './components/App.vue'
const v = new Vue({
el: "#app",
router,
render: h => h(App)
});
and my html file contain:
<div id="app"></div>
and I get this error:
vue.common.js:436 [Vue warn]: Failed to mount component: template or render function not defined.
found in
---> <Anonymous>
<App> at /opt/lampp/htdocs/gif/resources/assets/js/components/App.vue
<Root>
it happens because the facebook component, when I'm in the main page I don't see the error, only when I enter the facebook route
It seems your first set up was failing because of what build you we're using. For eg:
App.app = new Vue({
router,
render (h) {
return h(`div`, App.template) // this part can be roughly
// translated to `return h(`div`,
// `<one-component></one-component>
// <router-view></router-view>`)` and I believe
// this failed due to the fact that when you pass
// template string to the render method it needs to
// be compiled and your setup didn't account for that.
}
}).$mount('#app');
Your other set up ( as per suggestion of #wostex ) is much better but I think that here you are missing .$mount('#app') at the end of your Vue initialization. So:
const v = new Vue({
router,
render: h => h(App)
}).$mount('#app')
I looked at Laracasts in Jeffry tutorial about Vue
He did there like that:
const router = new VueRouter({
routes: [
{
path: '/',
},
{
path: '/facebook',
component: require('./components/facebook.vue')
}
]
});
and it work's
So thanks every one that tried to help me

Vue 2 Failed to mount component

I'm using Laravel 5.2 and Vue 2.0.6. If I use local components, it works fine. But when I try to use global component from another .vue file, it shows following error:
[Vue warn]: Failed to mount component: template or render function not defined. (found in component <test> at path\to\site\resources\assets\blog\components\test.vue)
Test.vue
<template>
<div>
<h1 class="hello">Hello</h1>
</div>
</template>
<style>
.hello {
color:blue;
}
</style>
<script>
export default {}
</script>
App.js
var Vue = require('vue');
var resource = require('vue-resource');
window.Vue = Vue;
Vue.use(resource);
Vue.component('test', require('../components/test.vue'));
new Vue({
el: '#app'
});
Gulpfile.js
var gulp = require('gulp');
var elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
require('laravel-elixir-webpack-official');
var blogResourcePath = './resources/assets/blog';
var blogPublicPath = 'public/blog-assets';
elixir(function(mix) {
mix.webpack('app.js', blogPublicPath + '/js', blogResourcePath + '/js')
});
Webpack.config.js
'use strict';
const path = require('path');
module.exports = {
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname, 'resources/assets'),
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.vue$/,
loader: 'vue',
},
{
test: /\.css$/,
loader: 'style!css'
},
]
},
resolve: {
alias: {
vue: 'vue/dist/vue.js',
}
}
};
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<test></test>
</div>
<script type="text/javascript" src="{{ elixir('blog-assets/js/app.js')}} ">
</html>
There is no compilation error. A similar question tis here but that doesn't solve my issues.
I guess that this is because with Vue2.0, the default version is the one without template parser. You need to import Vue as follows:
import Vue from 'vue/dist/vue.js'
Please check LinusBorg answer here:
https://forum-archive.vuejs.org/topic/4399/vue-2-0-vue-warn-failed-to-mount-component-template-or-render-function-not-defined-found-in-root-instance/6

dojo 1.7.2+ require custom module

I have written a custom modyle, for example it is printing "Hello World" to the console.
require([
"dojo/_base/declare"
],
function(declare) {
return [
declare("Hello", null, {
printHello : function() {
console.log("Hello, World!");
}
})
];
}
);
And the name of the .js file is "Hello.js". In my html page I need this module, but I have a problem with loading it. My code:
<script type="text/javascript">
var dojoConfig = {
async : true,
parseOnLoad : false,
isDebug : true,
packages: [
{ name: "gui", location: "/scripts/gui" }
]
};
require([
"gui/common/Hello"
],
function(HelloFunciton) {
var hello = new Hello();
hello.printHello();
});
</script>
But I have a error in console:
"NetworkError: 404 Not Found - http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/scripts/gui/common/Hello.js"
It should the javascript file from the localhost...
What might be the problem?
Add baseUrl: "./" to your dojoConfig.
Also make the path to your package relative via ./scripts/gui.
Complete HTML file:
<html>
<head>
<script>
var dojoConfig = {
async: true,
baseUrl: "./",
parseOnLoad: false,
isDebug: true,
packages: [
{ name: "gui", location: "./scripts/gui" }
]
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js"></script>
<script>
require(["gui/common/Hello"], function(Hello) {
var hello = new Hello();
hello.printHello();
});
</script>
</head>
<body>
</body>
</html>
The module file ./scripts/gui/common/Hello.js:
define([
"dojo/_base/declare"
], function(
declare
) {
return declare([], {
printHello: function() {
console.log("Hello world!");
}
});
});