React does not render on the page - gruntjs

I'm using the example from the react (0.14.2) blog:
var React = require('react');
var ReactDOM = require('react-dom');
var MyComponent = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
console.info('reactdom render');
ReactDOM.render(<MyComponent />, document.getElementById('whoopidoo'));
I compile it with grunt:
browserify: {
options: {
transform: [
['babelify', {
loose: 'all'
}]
]
},
And include the script in an html page:
<script src="1_basic_minimal.js" type="text/javascript"></script>
But the page is just blank, no errors, absolutely nothing. Is my compiling wrong perhaps?
edit
contents of file:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({},{},[]);

Related

Vue 3 component data binding doesn't work

In the following example, {{test}} doesn't get updated according to the input of the component. What am I doing wrong?
<html>
<body>
<Component v-model="test"></Component>
{{test}}
<script type="module">
import {createApp} from './node_modules/vue/dist/vue.esm-browser.prod.js';
const Component = {
props: {
modelValue: String,
},
emits: [
'update:modelValue',
],
template: `<input #keyup="updateValue">`,
methods: {
updateValue(event) {
this.$emit('update:modelValue', event.target.value);
},
},
};
const app = createApp({});
app.component('Component', Component);
app.mount('body');
</script>
</body>
</html>
You forget to declare test variable in data options.
const app = createApp({
data: () => {
return {
test: ''
}
}
});

Adding External Script to Specific Story in Storybook

I wanted to know how I can load in external javascript into a specific story in storybook. The only documentation I can find right now is how to do it globally https://storybook.js.org/docs/react/configure/story-rendering. Doing this works, i would just like to save on performance since only one of my stories uses an external js script.
No, there isn't a standard way to do this in storybook currently (version 6.5).
However you can achieve it with a decorator.
Depending on your needs it could look something like this (this is for a React story):
import { Story, Meta } from '#storybook/react';
import { useEffect } from '#storybook/addons';
export default {
title: 'My Story',
component: MyStory,
decorators: [
(Story) => {
useEffect(() => {
const script = document.createElement('script');
script.src = '/my-script';
document.body.appendChild(script);
}, []);
return <Story />;
},
],
};
There are some caveats here though:
The scripts will remain loaded as you navigate to other stories.
The story will render before the script has loaded.
To handle these caveats you can:
Add a cleanup handler to useEffect.
Don't render your <Story/> until the script has loaded.
For example:
import { Story, Meta } from '#storybook/react';
import { useEffect, useState } from '#storybook/addons';
export default {
title: 'My Story',
component: MyStory,
decorators: [
(Story) => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
const script = document.createElement('script');
script.onload = () => {
setIsLoaded(true);
};
script.src = '/my-script';
document.body.appendChild(script);
return () => {
// clean up effects of script here
};
}, []);
return isLoaded ? <Story /> : <div>Loading...</div>;
},
],
};
If you have multiple scripts you'll have to wrap all the onload events into a Promise.all.
This could be wrapped up in an addon similar to storybook-addon-run-script.

vue mpa fails to compile when adding css to <style> tags

I have an MPA app, where vue.js is used as a part of the application. I have a very simple test set up, here:
relevant parts of my template
....
<div id='app-basket-checkout'>
<h1>Better Be Here</h1>
</div>
....
pageBasketCheckout.js (essentially my app.js)
import Vue from 'vue'
import AppBasketCheckout from './BasketCheckout.vue'
import './dummyScss.css'
Vue.config.productionTip = false
new Vue({
render: h => h(AppBasketCheckout)
}).$mount('#app-basket-checkout')
component
<template>
<div id="app-basket-checkout">
{{msg}}
</div>
</template>
<script>
export default {
name: 'AppBasketCheckout',
components: {
},
data() {
return {
msg: 'Hello'
}
}
}
</script>
<style scoped>
</style>
So the above code renders just fine in my front end. I end up with an extra div that has hello printed inside, well done.
However when I add css to the style tag:
<template>
<div id="app-basket-checkout">
{{msg}}
</div>
</template>
<script>
export default {
name: 'AppBasketCheckout',
components: {
},
data() {
return {
msg: 'Hello'
}
}
}
</script>
<style scoped>
body {
font-family: Arial, Helvetica, sans-serif;
line-height: 1.4;
}
</style>
This produces this error in chrome:
Uncaught Error: Cannot find module './BasketCheckout.vue?vue&type=style&index=0&id=2711cf65&scoped=true&lang=css&'
at webpackMissingModule (VM45512 BasketCheckout.vue:4)
at eval (VM45512 BasketCheckout.vue:4)
at Module../src/BasketCheckout.vue (pageBasketCheckout.bundle.js:40)
at __webpack_require__ (index.bundle.js:4312)
at eval (pageBasketCheckout.js:3)
at Module../src/pageBasketCheckout.js (pageBasketCheckout.bundle.js:29)
at __webpack_require__ (index.bundle.js:4312)
at checkDeferredModulesImpl (index.bundle.js:4453)
at webpackJsonpCallback (index.bundle.js:4435)
at pageBasketCheckout.bundle.js:9
Again this error only happens when adding css to the component. Here is my webpack.config.js:
const path = require('path');
const webpack = require('webpack')
const glob = require('glob')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
watch: true,
context: path.resolve(__dirname, 'uniquesite/uniquesite'),
mode: 'development',
entry: {
index: {
import: ['#babel/polyfill', './src/index.js'],
// dependOn: ['babel'],
},
pageProductDetails: {
import: ['#babel/polyfill', './src/pageProductDetails.js'],
dependOn: ['index'],
},
pageBasketCheckout: {
import: ['#babel/polyfill', './src/dummyScss.scss', './src/pageBasketCheckout.js'],
dependOn: ['index']
}
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'uniquesite/uniquesite/static/uniquesite/js/'),
},
plugins: [
new VueLoaderPlugin()
],
resolve: {
alias: {
jquery: "jquery/src/jquery",
'jquery-ui': "jquery-ui-dist/jquery-ui.js",
boostrap: "bootstrap/dist/js/bootstrap.bundle.js"
}
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader'
},{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
};
You'll note I've also tried importing a dummy .css file to ensure the style loader works, as I've seen one more SO question with a similar problem that solved it that way. That didn't work for me however.
Update 1
My current thinking is that the problem has to be happening in the VueLoaderPlugin. That plugin is reponsible for splitting the script into distinct parts for template, logic, and style. It looks like the style is not actually making it into the bundle. See below.
"use strict";
eval(
"__webpack_require__.r(__webpack_exports__);
/* harmony import */
var _BasketCheckout_vue_vue_type_template_id_2711cf65___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(
/*! ./BasketCheckout.vue?vue&type=template&id=2711cf65& */
\"./src/BasketCheckout.vue?vue&type=template&id=2711cf65&\"
);
/* harmony import */
var _BasketCheckout_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(
/*! ./BasketCheckout.vue?vue&type=script&lang=js& */
\"./src/BasketCheckout.vue?vue&type=script&lang=js&\"
);
Object(function webpackMissingModule() {
var e = new Error(
\"Cannot find module './BasketCheckout.vue?vue&type=style&index=0&lang=css&'\"
); e.code = 'MODULE_NOT_FOUND';
throw e;
}());
/* harmony import */
var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(
/*! !../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */
\"../../node_modules/vue-loader/lib/runtime/componentNormalizer.js\"
);
/* normalize component */
var component = (
0,_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__.default
)(
_BasketCheckout_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__.default,
_BasketCheckout_vue_vue_type_template_id_2711cf65___WEBPACK_IMPORTED_MODULE_0__.render,
_BasketCheckout_vue_vue_type_template_id_2711cf65___WEBPACK_IMPORTED_MODULE_0__.staticRenderFns,
false,
null,
null,
null)
/* hot reload */
if (false) { var api; }
component.options.__file = \"src/BasketCheckout.vue\"
/* harmony default export */
__webpack_exports__[\"default\"] = (component.exports);
//# sourceURL=webpack:///./src/BasketCheckout.vue?"
);
Scoped CSS rules only apply to the current component (and its child components' root nodes).
You are mounting your Vue instance at #app-basket-checkout, which is already inside a <body> element.
You can style <body>, but do it using a global stylesheet that is imported in your app.js, not a subcomponent.
Alternatively, you can apply a class-based style at a low level node within your Vue instance and likely deliver your desired styles.

how to configure rollup vue3 environment

when I use rollup configure vue3 environment ,i run it then use the component in the html file,it happen error
the code below
rollup.config.js this is rollup config file
const path = require('path')
const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const babel = require('rollup-plugin-babel')
const json = require('rollup-plugin-json')
const vue = require('rollup-plugin-vue')
const postcss = require('rollup-plugin-postcss')
const inputPath = path.resolve(__dirname,'./src/index.js')
const outputUmdPath = path.resolve(__dirname,'./dist/imooc.datav.js')
const outputEsPath = path.resolve(__dirname,'./dist/imooc.datav.es.js')
module.exports = {
input:inputPath,
output:[{
file:outputUmdPath,
format:'umd',
name:'imoocDatav',
globals: {
vue: 'Vue'
}
},{
file:outputEsPath,
format:'es',
globals: {
vue: 'Vue'
}
}],
plugins:[
vue(),
babel({
exclude:'node_modules/**',
presets: ["#vue/babel-preset-jsx"]
}),
resolve(),
commonjs(),
json(),
// vue(),
postcss({
plugins:[]
})
],
external:['vue']
}
Test.vue this is vue3 component
<template>
<div class="text">{{ aa }}</div>
</template>
<script>
export default {
name: 'Test',
setup() {
const aa = 'hello';
return {
aa,
};
},
};
</script>
<style lang="scss" scoped>
.text {
color: red;
}
</style>
index.js the code make an global component
import Test from './Test.vue'
export default function(Vue){
Vue.component(Test.name,Test);
}
index.html this is html file
<!DOCTYPE html>
<html>
<head>
<title>imooc datav libs example</title>
<script src="https://cdn.jsdelivr.net/npm/vue#3.0.0-beta.6/dist/vue.global.js"></script>
<script src="../dist/imooc.datav.js"></script>
</head>
<body>
<div id="app">
{{message}}
<test></test>
</div>
<script>
Vue.createApp({
setup(){
var message = 'hello world';
return {
message
}
}
}).use(imoocDatav).mount('#app');
</script>
</body>
</html>
vue.global.js:4877 TypeError: Cannot read property 'aa' of undefined
package.json dependencies:
"vue": "^3.0.0"
Change:
external:['vue']
to
external:['#vue']
This works for me

Assign ReactJs Props to FlowRouter

How do I pass the props from FlowRouter to my react component. Is that possible? The documentation is that great.
Im doing something like this:
FlowRouter.route('/dashboard', {
name: 'dashboard',
action(){
var x = Projects.find().fetch(); // this not working
console.log(x); // x is []. Why?
ReactLayout.render(App, {
nav: <Nav />,
content: <Profile data={x}/>
});
}
});
In my app I wish to say this.props.data but the array is empty. I have to put the logic into the react component. Is that the correct way? I hope not.
I think you need subscriptions... see documentation here https://github.com/kadirahq/flow-router#subscription-management
FlowRouter.route('/dashboard', {
name: 'dashboard',
subscriptions(){
this.register('myProjects', Meteor.subscribe('projects'));
},
action(){
ReactLayout.render(App, {
nav: <Nav />,
content: <Profile data={myProjects}/>
});
}
});
But after further review, they are actually recommending that you do get the meteor data in the React Component... see documentation here
https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management/with-react
Profile = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
var data = {};
var handle = Meteor.subscribe('projects');
if(handle.ready()) {
data.projects = Projects.find({});
}
return data;
},
});
Sample Project: https://github.com/aaronksaunders/meteor-react-demo2

Resources