How to configure Relay.JS in Vite? - javascript

I'm trying to migrate my React project from CRA to Vite, this is my vite.config.js:
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import envCompatible from 'vite-plugin-env-compatible'
import relay from "vite-plugin-relay"
import macrosPlugin from "vite-plugin-babel-macros"
import path from 'path';
import fs from 'fs/promises';
export default defineConfig({
resolve: {
alias: {
'~': path.resolve(__dirname, 'src'),
'#material-ui/core': path.resolve(__dirname, 'node_modules/#material-ui/core')
}
},
esbuild: {
loader: "tsx",
include: /src\/.*\.[tj]sx?$/,
exclude: [],
},
optimizeDeps: {
esbuildOptions: {
plugins: [
{
name: "load-js-files-as-jsx",
setup(build) {
build.onLoad({ filter: /src\/.*\.js$/ }, async (args) => ({
loader: "tsx",
contents: await fs.readFile(args.path, "utf8"),
}));
},
},
],
},
},
define: {
global: {},
},
plugins: [
envCompatible(),
react(),
relay,
//macrosPlugin(),
],
})
My GraphQL query files are like this:
import graphql from 'babel-plugin-relay/macro'
const getQuery = () => graphql`
query UserQuery($id: ID!) {
user(id: $id) {
id
fullName
}
}
`
export default getQuery
When I tried to run the project in dev mode (command $ vite), I got this error:
So I did some search and replaced vite-plugin-relay to vite-plugin-babel-macros like this:
// others import
import relay from "vite-plugin-relay"
import macrosPlugin from "vite-plugin-babel-macros"
export default defineConfig({
// configs like bellow
plugins: [
envCompatible(),
react(),
//relay,
macrosPlugin(),
],
})
So I started to get a new error:
How can I configure Relay to work on Vite.JS?

Might be a bit late, but the issue has been fixed in Relay#13 and you can find some workarounds in this thread for older versions of Relay :
https://github.com/facebook/relay/issues/3354
You can also try adding the option eagerEsModules: true to your relay babel plugin configuration.

Unless you have some specific usecase that requires the use of babel-plugin-relay, your issue should be resolved if you change your imports from
import graphql from 'babel-plugin-relay/macro'
to
import { graphql } from "react-relay";
You should only need the relay vite plugin at that point, and can remove vite-plugin-babel-macros

There's a few things wrong with your setup.
1. Don't use vite-plugin-babel-macros:
Use #vitejs/plugin-react instead.
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import relay from "vite-plugin-relay";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [relay, react({
babel: {
plugins: ['babel-plugin-macros']
},
})],
});
You can probably get it to work with vite-plugin-babel-macros, but the later is an official plugin.
2. Don't use 'babel-plugin-relay/macro':
Use the following instead:
import { graphql } from "react-relay";
It's unclear to me why the official docs suggest using babel-plugin-relay/macro, but that just doesn't work.
3. Configure relay.config.js correctly:
{
"src": "./src",
"language": "typescript",
// Change this to the location of your graphql schema
"schema": "./src/graphql/schema.graphql",
"exclude": [
"**/node_modules/**",
"**/__mocks__/**",
"**/__generated__/**"
],
"eagerEsModules": true
}
In particular, make sure you use language: typescript and eagerEsModules.
4. Sample repository
I wrote a sample repository showing how to properly configure React Relay with Vite.js and TypeScript, you can find it here.

Related

Problems with Amplify and Vite

I am getting errors while setting up Amplify Authentication with React and Vite.
This is what I have tried already.
Packages used:
"#aws-amplify/ui-react": 4.2.0
"aws-amplify": 5.0.5
Main.jsx
import Amplify from "aws-amplify"
import awsExports from "./aws-exports"
Amplify.configure(awsExports)
vite.config.js
import { defineConfig } from 'vite'
import postcss from './postcss.config.js'
import react from '#vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
define: {
'process.env': process.env,
'global': {}
},
css: {
postcss,
},
plugins: [react()],
resolve: {
alias: [
{
find: /^~.+/,
replacement: (val) => {
return val.replace(/^~/, "");
},
},
{
find: './runtimeConfig', replacement: './runtimeConfig.browser',
}
],
},
build: {
commonjsOptions: {
transformMixedEsModules: true,
}
}
})
Running, npm run dev, app crashes and console has this error:
'Uncaught SyntaxError: The requested module '/node_modules/.vite/aws-amplify.js?v=d4f24853' does not provide an export named 'default' (at main.jsx:5:1)'

Rollup imported css in a webcomponent

I am creating simple webcomponent now I want to import css , I found a method using adpotedstylesheet.
Here is how I import it my webcomponet
import sheet from './styles/swal.css' assert { type: 'css' };
class Demo extends HTMLElement{
constructor() {
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(Demo.content.cloneNode(true));
document.adoptedStyleSheets = [sheet];
this.shadowRoot.adoptedStyleSheets = [sheet];
}
}
window.customElements.define("demo-component", Demo);
and here is my rollup settup for bundling my component
import summary from "rollup-plugin-summary";
import { terser } from "rollup-plugin-terser";
import resolve from "#rollup/plugin-node-resolve";
import replace from "#rollup/plugin-replace";
import postcss from "rollup-plugin-postcss";
import { eslint } from "rollup-plugin-eslint";
import babel from "rollup-plugin-babel";
import { uglify } from "rollup-plugin-uglify";
import commonjs from 'rollup-plugin-commonjs';
export default {
input: "index.js",
output: {
file: "dist/index.js",
format: "esm",
},
onwarn(warning) {
if (warning.code !== "THIS_IS_UNDEFINED") {
console.error(`(!) ${warning.message}`);
}
},
plugins: [
postcss({
plugins: [],
extensions: [".css"],
}),
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs(),
eslint({
exclude: ["src/styles/**"],
}),
babel({
exclude: "node_modules/**",
}),
terser({
ecma: 2017,
module: true,
warnings: true,
mangle: {
properties: {
regex: /^__/,
},
},
}),
summary(),
replace({
"Reflect.decorate": "undefined",
preventAssignment: true,
ENV: JSON.stringify(process.env.NODE_ENV || "development"),
}),
process.env.NODE_ENV === "production" && uglify(),
],
};
Now when i run npm run buil I get the following error.
[!] (plugin commonjs) SyntaxError: Unexpected token (3:38)`
What am I doing wrong here ???
Currenly, Rollup doesn't support import assertions. There is open issue for Rollup to address it. There is an experimental Rollup plugin that supports this but it seems to have some issues.
Another option you can try is to use rollup-string-plugin. You can use it to read CSS file as a string and then build your constructible stylesheets and assign it to adoptedStyleSheets property as explained here for Webpack. Following is one example of doing it..
// Read SCSS file as a raw CSS text
import styleText from './my-component.css';
const sheet = new CSSStyleSheet();
sheet.replaceSync(styleText);
// Custom Web component
class FancyComponent1 extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
// Attaching the style sheet to the Shadow DOM of this component
shadowRoot.adoptedStyleSheets = [sheet];
shadowRoot.innerHTML = `
<div>
<p>Hello World</p>
</div>
`;
}
}
Side note: With Webpack, you can use raw-loader.
Be aware that adoptedStyleSheets is currently not supported by Safari on Mac and iOS. But, Rollup might handle this for you - I don't know.
Another solution is to check out:
https://www.npmjs.com/package/csshtml-module
This CLI tool can be set up to let you automatically compile CSS/HTML to native JS modules.
I created that CLI tool to tackle this issue. It might not be for everyone - but maybe it resonate with you.

Rollup + React 17 with new JSX Transform - "React is not defined"

I'm trying to prototype a microfrontend architecture with Rollup and a couple of create-react-app applications. However when I locally yarn link my external app with the container app, I run into the following error:
ReferenceError: React is not defined
23500 | return /#PURE/React.createElement("div", {
| ^ 23501 | id: "container",
23502 | className: "flex flex-col h-screen"
23503 | }, /#PURE/React.createElement(BrowserRouter, null, /#PURE/React.createElement(Header, {
I think it's because we're not importing React at the top of every component/file because of React 17's new JSX Transform allowing you to not have to do that. I'd really like to be able to build our micro frontend package without having to import React in every file, is there a way to do this?
Here is the rollup.config.js:
import babel from 'rollup-plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import resolve from '#rollup/plugin-node-resolve';
import image from '#rollup/plugin-image';
import visualizer from 'rollup-plugin-visualizer';
import includePaths from 'rollup-plugin-includepaths';
import replace from '#rollup/plugin-replace';
import pkg from './package.json';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
export default {
input: './src/App.jsx',
output: [
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'esm',
},
],
plugins: [
external(),
postcss(),
resolve({
mainFields: ['module', 'main', 'jsnext:main', 'browser'],
extensions,
}),
image(),
visualizer(),
includePaths({ paths: ['./'] }),
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
babel({
exclude: 'node_modules/**',
plugins: [
[
'module-resolver',
{
root: ['src'],
},
],
],
presets: ['#babel/preset-react'],
}),
commonjs(),
],
};
In tsconfig.json, add the following code
{
"compilerOptions": {
"jsx": "react-jsx",
}
}
Fixed this by adding { runtime: "automatic" } to the #babel/preset-react preset.
From the preset-react runtime docs:
automatic auto imports the functions that JSX transpiles to. classic does not automatic import anything.
Also mentioned in the React post about the new JSX transform:
Currently, the old transform {"runtime": "classic"} is the default option. To enable the new transform, you can pass {"runtime": "automatic"} as an option to #babel/plugin-transform-react-jsx or #babel/preset-react
Here's a sample:
{
// ...
plugins: [
// ...
babel({
// ...
presets: [
// ...
["#babel/preset-react", { runtime: "automatic" }],
]
})
]
}

Svelte Component Testing with Jest, Unable to load Svelte files recursively

I am working on a Svelte Project with Typescript and want to use Jest to test UI components using the #testing-library/svelte module . I am not able to properly import all my svelte files like my sub-components and Jest just hangs trying to load the application.
There are some typescript errors in the svelte components and by these errors printing, I can see which files actually loaded. After loading App.svelte, the program just freezes and doesn't load any of the submodules.
I am not exactly sure where the error is, because before this error I was getting an import error similar to jest: Test suite failed to run, SyntaxError: Unexpected token import, I "solved" this by adding the configuration to the .babelrc file and adding the preprocessor.
All the relevant files are below and are also on Github here
The actual test case file, there is a data-testid element called dropzone in dropzone.svelte
// app.spec.js
import App from "../src/App.svelte";
import { render, fireEvent } from "#testing-library/svelte";
describe("UI Load Test", () => {
it("Check Dropzone Loaded", () => {
const { getByText, getByTestId } = render(App);
const dropzone = getByTestId("dropzone");
expect(dropzone).toBeDefined();
});
});
// App.svelte
<script lang="ts">
...
// Static Svelte Components
import HeaderContent from "./components/header.svelte";
import Loader from "./components/loader.svelte";
import Footer from "./components/footer.svelte";
// Dynamic Svelte Modules
import Terminal from "./modules/terminal/terminal.svelte";
import Dropzone from "./modules/dropzone/dropzone.svelte";
import Configure from "./modules/configure/configure.svelte";
import Video from "./modules/video/video.svelte";
import Progress from "./modules/progress/progress.svelte";
let loaded = $loadedStore;
...
let fileState = $fileUploaded;
...
let processedState = $processed;
...
let progressState = $progressStore;
...
let configState = $showConfig;
...
</script>
...
// jest.config.js
const {
preprocess: makeTsPreprocess,
createEnv,
readConfigFile,
} = require("#pyoner/svelte-ts-preprocess");
const env = createEnv();
const compilerOptions = readConfigFile(env);
const preprocessOptions = {
env,
compilerOptions: {
...compilerOptions,
allowNonTsExtensions: true,
},
};
const preprocess = makeTsPreprocess(preprocessOptions);
module.exports = {
transform: {
"^.+\\.svelte$": [
"jest-transform-svelte",
{ preprocess: preprocess, debug: true },
],
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": "babel-jest",
},
moduleDirectories: ["node_modules", "src"],
testPathIgnorePatterns: ["node_modules"],
bail: false,
verbose: true,
transformIgnorePatterns: ["node_modules"],
moduleFileExtensions: ["js", "svelte", "ts"],
setupFilesAfterEnv: [
"./jest.setup.js",
"#testing-library/jest-dom/extend-expect",
],
};
// babel.config.js
module.exports = {
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current",
},
},
],
],
};
//.babelrc
{
"plugins": [
"#babel/plugin-syntax-dynamic-import"
],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
You have not imported these variables yet from your store.ts file "$loadedStore, $fileUploaded, $processed, $progressStore, $showConfig"
Basically, you can put this on a store.ts like this.
// store.ts
export const loadedStore= writable([]) // for arrays
export const fileUploaded= writable({}) // for objects
export const processed = writable("") // for strings
export const progressStore = writable("")
export const showConfig= writable({})
Then add this line on top of your App.svelte file
// App.svelte
import { loadedStore, fileUploaded, processed, progressStore, showConfig } from 'store.ts'

Babel React transform : Property value expected type of string but got null

I have an application that is working great client side (transpiled and compiled with Webpack/Babel).
I'm trying to render this app server side with Node, but I'm getting this error :
TypeError: C:/[PROJECT_PATH]/src/_base/common/components/general/AComponent.js: Property value expected type of string but got null
at Object.validate (C:\[PROJECT_PATH]\node_modules\babel-types\lib\definitions\index.js:153:13)
at validate (C:\[PROJECT_PATH]\node_modules\babel-types\lib\index.js:269:9)
at Object.builder (C:\[PROJECT_PATH]\node_modules\babel-types\lib\index.js:222:7)
at File.<anonymous> (C:\[PROJECT_PATH]\node_modules\babel-core\lib\transformation\file\index.js:329:56)
at File.addImport (C:\[PROJECT_PATH]\node_modules\babel-core\lib\transformation\file\index.js:336:8)
at C:\[PROJECT_PATH]\node_modules\babel-plugin-react-transform\lib\index.js:257:46
at Array.map (native)
at ReactTransformBuilder.initTransformers (C:\[PROJECT_PATH]\node_modules\babel-plugin-react-transform\lib\index.js:255:40)
at ReactTransformBuilder.build (C:\[PROJECT_PATH]\node_modules\babel-plugin-react-transform\lib\index.js:164:41)
at PluginPass.Program (C:\[PROJECT_PATH]\node_modules\babel-plugin-react-transform\lib\index.js:331:17)
It happens on any component imported.
I know the components themselves work because they do in client mode.
Here is my index.js (same babel config as in client side app) :
require('babel-register')({
presets:["es2015", "stage-0",'react'],
highlightCode: false,
sourceMaps: "both",
env: {
development: {
plugins: [
'transform-decorators-legacy',
["react-transform", {
transforms: [{
imports: ['react'],
locals: ['module']
}]
}]
]
}
}
});
require('./renderer.js');
Here is my renderer.js :
import React, { Component } from 'react'
import Router, {match, RoutingContext } from 'react-router'
// this works :
import AnyActions from 'path/to/actions/AnyActions'
// this don't
import AnyComponent from 'path/to/any/component'
Everything else is commented out !
I tried to import this simple AComponent :
import React, { Component, PropTypes } from 'react'
export default class AComponent extends Component {
render () { return (<p>Hello</p>)}
}
Same error !
I must miss something obvious ... but I don't see it !
Problem was with my Babel's React-Transform incorrect configuration : I was specifiying import and locals without any transform name ...
Removing this part solved my problem.
Here is my new index.js :
require('babel-register')({
presets:["es2015", "stage-0",'react'],
highlightCode: false,
sourceMaps: "both",
env: {
development: {
plugins: [
'transform-decorators-legacy'
]
}
}
});
require('./renderer.js');

Categories

Resources