Vue 2 Failed to mount component - gulp

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

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"
}
}

Html-loader + file-loader not bundling the correct image source

I'm planning to use Webpack for a project and I'm setting up my workflow with Html-loader + file-loader to get a production html file with dynamic src for the images, as Colt Steele teaches in this video. Here are my src/ files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Popular on Letterboxd</title>
</head>
<body>
<img src="./assets/chira.jpg" />
</body>
</html>
index.js:
import img from './assets/chira.jpg';
import "./main.css";
And main.css
body {
background-color: darkblue;
}
These are my config files (I have an individual for dev and production and a common for both):
webpack.common.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
devtool: "none",
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
publicPath: 'assets',
outputPath: 'assets/img'
}
}
]
}
],
},
};
webpack.dev.js:
const path = require('path');
const common = require("./webpack.common");
const merge = require('webpack-merge');
module.exports = merge(common, {
mode: "development",
devServer: {
contentBase: path.join(__dirname, 'src'),
},
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
});
And webpack.prod.js:
const path = require('path');
const common = require("./webpack.common");
const merge = require('webpack-merge');
module.exports = merge(common, {
mode: "production",
output: {
filename: "main.[contentHash].js",
path: path.resolve(__dirname, "dist")
},
});
However, when I run npm run build, which executes this command:
"build": "webpack --config webpack.prod.js"
And I get the expected dist folder with assets/img/[name].[hash].[ext], but in my index.html I do not get the expected src tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Popular on Letterboxd</title>
</head>
<body>
<img src="[object Module]" />
<script type="text/javascript" src="main.e55bd4ff82bf2f5cec90.js"></script></body>
</html>
I've been trying to fix the problem for a while now, but I can't seem to get a proper answer anywhere, and nothing that I've tried have worked so far. I would appreciate if anyone who has encountered this problem can address how they fixed it, or if someone has any clue of what the problem might be and what can I do. Thanks in advance!
If you are using webpack 5 or later, the file-loader is depricated. File loader documentation
You could use the module asset/resource instead. Remove your file-loader rule and add the following rule to your module in webpack.common.js
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource'
}
]
},
then add assetModuleFilename in the output in your webpack.prod.js
output: {
assetModuleFilename: "assets/img/[name].[hash][ext]"
}
and keep your html-loader rule in the webpack.common.js as it is.
References Asset Modules
If file-loader verions is 5.0 then. Adding another option on file-loader as "esModule: false" will solve this problem.
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
publicPath: 'assets',
outputPath: 'assets/img',
esModule: false
}
}
]
}

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

React code not showing in browser

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>

Webpack paths issue with es6

I have a structure like this but am having an error when trying to run webpack
/app
/main.js
/foo.js
/dist
index.html ( uses <script src="dist/bundle.js"></script>)
webpackconfig.js
in main.js:
import foo from './foo'
var foo = new foo()
foo.js:
export class foo {
constructor() {
loadScript("//www.parsecdn.com/js/parse-1.4.0.min.js", init());
}
}
webpackconfig.js
My config:
module.exports = {
context: __dirname + "/app",
entry: "./main.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devtool: "#source-map",
module: {
loaders: [
// Transpile any JavaScript file:
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
},
resolve: {
// you can now require('file') instead of require('file.js')
extensions: ['', '.js', '.json']
}
}
but I get this error:
ERROR in ./main.js
Module not found: Error: Cannot resolve module 'foo'
It is because webpack try to load foo from node_modules directory.
You have to specify the path of your module like this:
import foo from './foo'