I am integrating Vite SSR to existing vue project. I copied vite configuration from SSR playground project and bumped ionic version to 6 because of dynamic loading issue from stencil.
After upgrading, it isn't compiling, showing this error.
12:03:15 AM [vite] Error when evaluating SSR module /src/components/ImportType.vue:
/data/Work/ssr-vue/node_modules/#ionic/core/components/ion-accordion.js:4
import { proxyCustomElement, HTMLElement, h, Host } from '#stencil/core/internal/client';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Here is my vite.config.js file
const vuePlugin = require('#vitejs/plugin-vue')
const vueJsx = require('#vitejs/plugin-vue-jsx')
const virtualFile = '#virtual-file'
const virtualId = '\0' + virtualFile
const nestedVirtualFile = '#nested-virtual-file'
const nestedVirtualId = '\0' + nestedVirtualFile
/**
* #type {import('vite').UserConfig}
*/
module.exports = {
plugins: [
vuePlugin(),
vueJsx(),
{
name: 'virtual',
resolveId(id) {
if (id === '#foo') {
return id
}
},
load(id) {
if (id === '#foo') {
return `export default { msg: 'hi' }`
}
}
},
{
name: 'virtual-module',
resolveId(id) {
if (id === virtualFile) {
return virtualId
} else if (id === nestedVirtualFile) {
return nestedVirtualId
}
},
load(id) {
if (id === virtualId) {
return `export { msg } from "#nested-virtual-file";`
} else if (id === nestedVirtualId) {
return `export const msg = "[success] from conventional virtual file"`
}
}
}
],
ssr: {
external: ["npm: #ionic/vue"]
},
build: {
minify: false
}
}
Please help me.
Related
I am working with a full stack GraqlQL based application. The server is working fine and now I need to try out the first queries and mutations on the client side. For some reason, the "monitoring" route, and everything that follows it, is not displayed. Below I will show the files that I have edited or created.
items.graphql:
query {
items {
_id
name
}
}
environment.js:
'use strict';
module.exports = function(environment) {
let ENV = {
apollo: {
apiURL: 'http://localhost:5000/graphql'
},
modulePrefix: 'client',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
//
},
EXTEND_PROTOTYPES: {
Date: false
}
},
APP: {
//
}
};
if (environment === 'development') {
//
}
if (environment === 'test') {
ENV.locationType = 'none';
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
//
}
return ENV;
};
monitoring.js (route):
import Route from '#ember/routing/route';
import { queryManager } from 'ember-apollo-client';
import query from 'client/gql/items.graphql';
export default Route.extend({
apollo: queryManager(),
model() {
return this.apollo.watchQuery({ query }, 'items');
}
});
monitoring.hbs:
<h3>Monitoring</h3>
<div>
{{#each model as |item|}}
<h3>{{item.name}}</h3>
{{/each}}
</div>
{{outlet}}
Thank you for attention!
I see this error:
Uncaught (in promise) Error: fetch is not defined - maybe your browser targets are not covering everything you need?
The solution is to fix two things.
First is to put this in ember-cli-build.js:
'ember-fetch': {
preferNative: true
}
And fix the route file:
import Route from '#ember/routing/route';
import { queryManager } from 'ember-apollo-client';
import query from 'client/gql/queries/items.graphql';
export default Route.extend({
apollo: queryManager(),
async model() {
let queryResults = await this.apollo.watchQuery({ query }, 'items');
return Object.values(queryResults);
}
});
I am trying to build sub-pages for a projects category in Gatsby, each project parent page already generates the way it should but the sub-pages do not.
Each project can have zero to many sub-pages, I only want a sub-page to be generated if it exists. Data is coming from a headless CMS through GraphQL
My loop for generating these pages in gatsby-node.js currently looks like this:
result.data.allSanityProjects.edges.forEach(({ node }) => {
node.projectChildPages.map(childPage => {
if (node && node.projectChildPages.length > 0 && node.projectChildPages.slug) {
createPage({
path: childPage.slug + "/" + node.projectChildPages.slug,
component: projectsSubPages,
context: {
slug: childPage.slug + "/" + node.projectChildPages.slug,
},
});
}
});
});
});
This loops through the "allSanityProjects" part of this GrapQL query
{
allSanityDefaultPage {
edges {
node {
slug
}
}
}
allSanityProjects {
edges {
node {
slug
projectChildPages {
slug
}
}
}
}
}
The results of running just the allSanityProjects-query looks like this
{
"data": {
"allSanityProjects": {
"edges": [
{
"node": {
"slug": "project-3",
"projectChildPages": []
}
},
{
"node": {
"slug": "project-1",
"projectChildPages": [
{
"slug": "project-1"
},
{
"slug": "Doggolicious"
},
{
"slug": "no-cats"
}
]
}
},
{
"node": {
"slug": "Project-2",
"projectChildPages": []
}
}
]
}
}
}
Gatsby fails building the project child pages with the following error.
warn The GraphQL query in the non-page component
Exported queries are only executed for Page components. It's possible you're
trying to create pages in your gatsby-node.js and that's failing for some
reason.
If the failing component(s) is a regular component and not intended to be a page
component, you generally want to use a <StaticQuery> (https://gatsbyjs.org/docs/static-query)
instead of exporting a page query.
If you're more experienced with GraphQL, you can also export GraphQL
fragments from components and compose the fragments in the Page component
query and pass data down into the child component — https://graphql.org/learn/queries/#fragments
My template looks like this:
import React from "react";
import { useStaticQuery, graphql } from "gatsby";
import Layout from "../components/layout";
const BlockContent = require("#sanity/block-content-to-react");
const projectsSubPages = ({ data }) => {
const pageData = data.sanityProjects.projectChildPages;
return (
<Layout>
<BlockContent blocks={pageData._rawBlockContent} />
</Layout>
);
};
export const query = graphql`
query($slug: String!) {
sanityProjects(slug: { eq: $slug }) {
projectChildPages {
_rawBlockContent
slug
title
}
}
}
`;
export default projectsSubPages;
As far as I can tell my error is in my gatsby-node.js file, not in my template even though gatsby tells me my error is in my template. I've tried running the exact same templates as the others I use (just with different queries in them) and still get the same error.
My full gatsby-node.js file:
exports.createPages = ({ actions, graphql }) => {
const path = require(`path`);
const { createPage } = actions;
const projects = path.resolve("src/templates/projects.js");
const defaultPage = path.resolve("src/templates/defaultPage.js");
const projectsSubPages = path.resolve("src/templates/projectsSubPages.js");
return graphql(`
{
allSanityDefaultPage {
edges {
node {
slug
}
}
}
allSanityProjects {
edges {
node {
slug
projectChildPages {
slug
}
}
}
}
}
`).then((result) => {
if (result.errors) {
reporter.panic("failed to create pages ", result.errors);
}
result.data.allSanityDefaultPage.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: defaultPage,
context: {
slug: node.slug,
},
});
});
result.data.allSanityProjects.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: projects,
context: {
slug: node.slug,
},
});
});
result.data.allSanityProjects.edges.forEach(({ node }) => {
node.projectChildPages.map(childPage => {
if (node && node.projectChildPages.length > 0 && node.projectChildPages.slug) {
createPage({
path: childPage.slug + "/" + node.projectChildPages.slug,
component: projectsSubPages,
context: {
slug: childPage.slug + "/" + node.projectChildPages.slug,
},
});
}
});
});
});
};
code
result.data.allSanityProjects.edges.forEach(({ node }) => {
node.projectChildPages.map(childPage => {
if (node && node.projectChildPages.length > 0 && node.projectChildPages.slug) {
Condition doesn't have much sense there:
if you're in .map() then for sure node and node.projectChildPages.length > 0 are true
projectChildPages is an array so no projectChildPages.slug here
query
Your fetched data (source) doesn't contain _rawBlockContent so you can't query for this in page component.
I wanted to try out Deno, so I decided to make a simple single-page React app.
But, when I try to pull in ReactDOM from the CDN, I get a console error: react_dom_development_js_2 is undefined.
I think what's going on is it can't resolve the ReactDOM CDN, but I can reach it from my browser? I also tried replacing it with what the browser resolves it to (https://unpkg.com/react-dom#16.13.1/umd/react-dom.development.js), but I still end up with the same error. Maybe I'm using the deno bundle wrong?
index.jsx
import { React } from "https://unpkg.com/react#16/umd/react.development.js";
import { ReactDOM } from "https://unpkg.com/react-dom#16/umd/react-dom.development.js";
ReactDOM.render(<p>Hello</p>, document.findElementById("app"));
index.html
<html>
<head>
<title>Test with Deno</title>
</head>
<body>
<div id="app"></div>
<script src="index.bundle.js"></script>
</body>
</html>
I run deno bundle index.jsx index.bundle.js to create my bundle,
index.bundle.js
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// This is a specialised implementation of a System module loader.
// #ts-nocheck
/* eslint-disable */
let System, __instantiateAsync, __instantiate;
(() => {
const r = new Map();
System = {
register(id, d, f) {
r.set(id, { d, f, exp: {} });
},
};
async function dI(mid, src) {
let id = mid.replace(/\.\w+$/i, "");
if (id.includes("./")) {
const [o, ...ia] = id.split("/").reverse(),
[, ...sa] = src.split("/").reverse(),
oa = [o];
let s = 0,
i;
while ((i = ia.shift())) {
if (i === "..") s++;
else if (i === ".") break;
else oa.push(i);
}
if (s < sa.length) oa.push(...sa.slice(s));
id = oa.reverse().join("/");
}
return r.has(id) ? gExpA(id) : import(mid);
}
function gC(id, main) {
return {
id,
import: (m) => dI(m, id),
meta: { url: id, main },
};
}
function gE(exp) {
return (id, v) => {
v = typeof id === "string" ? { [id]: v } : id;
for (const [id, value] of Object.entries(v)) {
Object.defineProperty(exp, id, {
value,
writable: true,
enumerable: true,
});
}
};
}
function rF(main) {
for (const [id, m] of r.entries()) {
const { f, exp } = m;
const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
delete m.f;
m.e = e;
m.s = s;
}
}
async function gExpA(id) {
if (!r.has(id)) return;
const m = r.get(id);
if (m.s) {
const { d, e, s } = m;
delete m.s;
delete m.e;
for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
const r = e();
if (r) await r;
}
return m.exp;
}
function gExp(id) {
if (!r.has(id)) return;
const m = r.get(id);
if (m.s) {
const { d, e, s } = m;
delete m.s;
delete m.e;
for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
e();
}
return m.exp;
}
__instantiateAsync = async (m) => {
System = __instantiateAsync = __instantiate = undefined;
rF(m);
return gExpA(m);
};
__instantiate = (m) => {
System = __instantiateAsync = __instantiate = undefined;
rF(m);
return gExp(m);
};
})();
System.register(
"index",
[
"https://unpkg.com/react#16/umd/react.development.js",
"https://unpkg.com/react-dom#16/umd/react-dom.development.js",
],
function (exports_1, context_1) {
"use strict";
var react_development_js_1, react_dom_development_js_1;
var __moduleName = context_1 && context_1.id;
return {
setters: [
function (react_development_js_1_1) {
react_development_js_1 = react_development_js_1_1;
},
function (react_dom_development_js_1_1) {
react_dom_development_js_1 = react_dom_development_js_1_1;
},
],
execute: function () {
react_dom_development_js_1.ReactDOM.render(
react_development_js_1.React.createElement("p", null, "Hello"),
document.findElementById("app"),
);
},
};
},
);
__instantiate("index");
The issue here is due to the typical React and ReactDOM packages being written as commonJS packages.
Deno by default requires all modules to be written using ES Modules (ESM). https://github.com/pikapkg/react is a build of React and ReactDOM that use ESM, so they should be importable in Deno. link with CDN
There is a standard library module in deno that lets you use commonJS modules, though you'll need to be careful with them especially if they require node specific functionality: https://deno.land/std/node#commonjs-module-loading
TypeScript does not allow imports from html or that end in a file extension.
So for now you can ignore them using // #ts-ignore which will allow deno to work.
There is a visual studio code extension for deno but at the time of writing it seems to be a bit unstable.
If and when its working correctly you would be able to config deno to work on a per project basis by defining a settings folder in the root of your project e.g. .vscode/settings.json.
{
"deno.enable": true
}
I am running an easy Sharepoint Framework project in Visual Studio Code:
I have this structure:
My files are as follows:
ComplexCalculator.ts
export class ComplexCalculator {
public sqr(v1: number): number {
return v1*v1;
}
public multiply(v1:number, v2:number): number {
return v1*v2;
}
}
EasyCalculator.ts
export class EasyCalculator {
public sum(v1: number, v2: number): number {
return v1 + v2;
}
public subtraction(v1: number, v2: number): number {
return v1 - v2;
}
}
Calculator.ts
export * from './ComplexCalculator';
export * from './EasyCalculator';
Calculator.manifest.json
{
"$schema": "../../../node_modules/#microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "8de800b0-6a4f-4cb0-bf75-62c32e6ea66b",
"componentType": "Library",
"version": "0.0.1",
"manifestVersion": 2
}
On my config.json I have this:
{
"entries": [
{
"entry": "./lib/webparts/librarysample/LibrarysampleWebPart.js",
"manifest": "./src/webparts/librarysample/LibrarysampleWebPart.manifest.json",
"outputPath": "./dist/librarysample.bundle.js"
},
{
"entry": "./lib/libraries/calculator/Calculator.js",
"manifest": "./src/libraries/calculator/Calculator.manifest.json",
"outputPath": "./dist/calculator.bundle.js"
}
],
"externals": {
"#microsoft/sp-client-base": "node_modules/#microsoft/sp-client-base/dist/sp-client-base.js",
"#microsoft/sp-client-preview": "node_modules/#microsoft/sp-client-preview/dist/sp-client-preview.js",
"#microsoft/sp-lodash-subset": "node_modules/#microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",
"office-ui-fabric-react": "node_modules/office-ui-fabric-react/dist/office-ui-fabric-react.js",
"react": "node_modules/react/dist/react.min.js",
"react-dom": "node_modules/react-dom/dist/react-dom.min.js",
"react-dom/server": "node_modules/react-dom/dist/react-dom-server.min.js",
"calculator": "./dist/calculator.bundle.js"
},
"localizedResources": {
"librarysampleStrings": "webparts/librarysample/loc/{locale}.js"
}
}
and finally on my gulpfile.js
const gulp = require('gulp');
const build = require('#microsoft/sp-build-web');
var through = require('through2'),
util = require('gulp-util'),
spawn = require('child_process').spawn,
clean = require('gulp-clean'),
ts = require('gulp-typescript');
build.initialize(gulp);
var libsPath = 'lib/libraries';
var srcPath = 'src/libraries';
var calculatorLibraryFolder = 'calculator';
gulp.task('watch-calculator-lib', (cb) => {
var watcher = gulp.watch(`${srcPath}/${calculatorLibraryFolder}/**/*.ts`, ['update-calculator-typings']);
watcher.on('change', (event) => {
console.log(`File ${event.path} was ${event.type}, Rebuilding library typings...`);
});
});
gulp.task('update-calculator-typings', [
'update-calculator-typings:clean-old-typings',
'update-calculator-typings:get-latest-typings',
'update-calculator-typings:build-lib-typings'
], () => {
});
gulp.task('update-calculator-typings:clean-old-typings', () => {
return gulp.src(`${libsPath}/${calculatorLibraryFolder}/**`, { read: false })
.pipe(clean());
});
gulp.task('update-calculator-typings:get-latest-typings', ['update-calculator-typings:clean-old-typings'], () => {
var tsResult = gulp.src(`${srcPath}/${calculatorLibraryFolder}/**/*.ts`)
.pipe(ts({
outDir: `${libsPath}/${calculatorLibraryFolder}`,
module: 'umd',
declaration: true
}));
return tsResult.dts.pipe(gulp.dest(`${libsPath}/${calculatorLibraryFolder}`));
});
gulp.task('update-calculator-typings:build-lib-typings', ['update-calculator-typings:get-latest-typings'], () => {
return gulp.src(`${libsPath}/${calculatorLibraryFolder}/**/*.d.ts`)
.pipe(updateLibTypings('calculator.d.ts'))
.pipe(gulp.dest('./typings'));
});
var updateLibTypings = function (typingsFilePath, opt) {
var typings = ["declare module 'calculator' {"];
var latestFile;
function processTypings(file, encoding, cb) {
if (file.isNull() || file.isStream()) {
cb();
return;
}
latestFile = file;
var contents = file.contents.toString('utf8');
if (contents.indexOf('export declare class ') === -1) {
cb();
return;
}
contents = contents.replace('export declare class ', 'class ');
typings.push(contents);
cb();
}
function endStream(cb) {
if (!latestFile) {
cb();
return;
}
typings.push('}');
var file = latestFile.clone({ contents: false });
file.path = latestFile.base + typingsFilePath;
file.contents = new Buffer(typings.join('\r\n'));
this.push(file)
cb();
}
return through.obj(processTypings, endStream);
}
the typings file is generated correctly on the dist folder
calculator.d.ts
declare module 'calculator' {
class ComplexCalculator {
sqr(v1: number): number;
multiply(v1: number, v2: number): number;
}
class EasyCalculator {
sum(v1: number, v2: number): number;
subtraction(v1: number, v2: number): number;
}
}
However, when I try to reference it into my webpart file
import * as calculator from 'calculator';
and then I try to compile
I get this error
Error - typescript - src/webparts/librarysample/LibrarysampleWebPart.ts(13,29): error TS2307: Cannot find module 'calculator'.
Your code import * as calculator from 'calculator'; is wrong. You need to import modules in your project using relative paths. e.g.
import * as calculator from './path/to/Calculator';
More
Be careful about file casing. I prefer camelCase for consistency.
Master node_modules : https://nodejs.org/docs/latest/api/modules.html
I am trying to create a Todos example app using the generator-react-webpack from here. Everything works until I started using alt for the flux pattern. When I run the project using npm run, I got the following error:
TodoStore.js: Unexpected token (12:0)
10 | import _ from 'lodash';
11 |
12 | #datasource(CategorySource)
It complains about the line 12 above for the #datasource decorator. Below is the code from my TodoStore.js:
'use strict';
const alt = require('../alt');
const Actions = require('../actions');
import {decorate, bind, datasource} from 'alt/utils/decorators';
import CategorySource from '../sources/CategorySource';
import _ from 'lodash';
#datasource(CategorySource)
#decorate(alt)
class TodoStore {
constructor() {
this.state = {
user: null,
todos: null,
todosLoading: true
};
}
#bind(Actions.todosLoading)
todosLoading() {
this.setState({
todosLoading: true
});
}
#bind(Actions.todosReceived)
receivedTodos(todos) {
_(todos)
.keys()
.each((k) => {
todos[k].key = k;
})
.value();
this.setState({todos, todosLoading: false});
}
#bind(Actions.categoriesReceived)
receivedCategories(categories) {
let selectedCategory;
_(categories)
.keys()
.each((key, index) => {
categories[key].key = key;
if (index == 0) {
categories[key].selected = true;
selectedCategory = categories[key];
}
})
.value();
this.setState({categories, selectedCategory, todosDirty: true});
}
#bind(Actions.login)
login(user) {
this.setState({user: user});
}
}
export default alt.createStore(TodoStore);
I found this post for a similar problem, but I don't have any luck getting it to work by changing this line: test: /\.jsx?$/, in my webpack.config.js file.
found out the reason: because it does not recognize the ES7 decorator syntax. I created a file named .babelrc at the root and its content is:
{
"stage": 0
}
Now everything works! Hope this will help someone in the future.