How do Vite MPAs using the Vue plugin work? - javascript

I have a Vite app created and I need it to have multiple pages. I read the docs and found how to do this (can be found here), however when I run the server I get a blank page.
My vite.config.js file:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
const { resolve } = require('path')
module.exports = {
build: {
rollupOptions: {
input: {
home: resolve(__dirname, 'src/Home/index.html')
}
}
}
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()]
})
Here's what my file structure looks like:
Edit: I have changed the config to what tony posted below, but it is still showing a blank page.
Edit 2: I found out that you don't need to use the vite.config.js routing, there's an easier way
Create a copy of your main.js, App.vue, and index.html file and rename them to something different. After you rename them change the <script type="module" src="index.js"></script> to your new JS file, and change the .vue file import in your new main.js to your new .vue file. Here's my new structure:
All I did was copy the files and change the names and imports, and it worked!

You have two default exports in vite.config.js, but there should only be one:
module.exports = { 1️⃣
//...
}
export default defineConfig({ 2️⃣
//...
})
The config should be:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
home: resolve(__dirname, 'src/Home/index.html')
}
}
}
})
GitHub demo

Related

How to configure Relay.JS in Vite?

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.

Vite.js not emitting HTML files in multi page app

I have a multi page app that I'm trying to build with Vite.js (migrating from Webpack). When building the Vite + React example code I see that it emits:
dist/index.html
dist/assets/<various assets>
However, when I try to make a multi page app as shown in the docs none of the HTMLs are emitted (but the rest of the content of /assets/ is there). Why is this?
// vite.config.js excerpt:
import { defineConfig } from 'vite'
import { dirname } from 'path';
import { fileURLToPath } from 'url';
export default defineConfig({
root: 'client',
build: {
outDir: 'dist',
rollupOptions: {
input: {
main: dirname(fileURLToPath(import.meta.url + 'index.html')),
login: dirname(fileURLToPath(import.meta.url + 'login.html')),
}
}
},
});
Try using the URL for file input as specified in vite doc
main: new URL('./client/index.html', import.meta.url).pathname

why background color is not set while using scss and css?

I am using scss and css in my project . I have two file styles.css and styles.css.I imported both file in _app.js
import "../styles.scss";
import Head from "next/head";
import React from "react";
import App from "next/app";
import "../styles.css";
in style.css
a {
color: red;
}
and in my styles.scss
body {
background-color: aqua
}
but background color is not set .I am not sure why it is not set. I also using scss loader to compile my scss file.
here is my code
https://codesandbox.io/s/sharp-jennings-upb7y?file=/styles.scss:0-33
NOTE ::To run this project you need to create new terminal and run a command npm run dev. because it run on 3004 port
my webpack-config
const withSass = require("#zeit/next-sass");
module.exports = (phase, { defaultConfig }) => {
return withCss(
withSass({
webpack(config, { isServer }) {
config.module.rules.push({
rules: [
{
test: /\.s[ac]ss$/i,
use: [
{
loader: "sass-loader",
options: {
additionalData: `$public_font_url: ${process.env.NEXT_PUBLIC_FONTS};`
}
}
]
}
]
});
return config;
}
})
);
};
Here is the solution, you must use the Head tag provided by next.js, there is no problem in your config file
https://codesandbox.io/s/relaxed-sea-khlgr?file=/pages/index.js

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'

#storybook/angular cannot load scss file on stories index

I have been trying to use storybook for my angular project and I use this guide https://storybook.js.org/basics/guide-angular/
I use the recommended config for webpack for sass loader for scss files and the scss file related to the project works fine, but if I import a scss file in the stories index.ts file, this file it is not loaded.
stories/index.ts
import { storiesOf } from '#storybook/angular';
import { action } from '#storybook/addon-actions';
import { VideoPosterComponent } from '../src/app/modules/ui-common/video-poster/video-poster.component';
//This scss it is not loaded
import '../src/styles.scss';
storiesOf('Video Poster component', module)
.add('Video Poster with author data', () => ({
component: VideoPosterComponent,
props: {
title: "Cinemagraph With Custom title",
subtitle: "This is a custom subtitle!"
}
}))
.add('Video Poster without author data', () => ({
component: VideoPosterComponent,
props: {}
}));
.storybook/webpack.config.js (recommended in here --> https://storybook.js.org/basics/guide-angular/#configure-style-rules)
const genDefaultConfig = require('#storybook/angular/dist/server/config/defaults/webpack.config.js');
module.exports = (baseConfig, env) => {
const config = genDefaultConfig(baseConfig, env);
// Overwrite .css rule
const cssRule = config.module.rules.find(rule => rule.test && rule.test.toString() === '/\\.css$/');
if (cssRule) {
cssRule.exclude = /\.component\.css$/;
}
// Add .scss rule
config.module.rules.unshift({
test: /\.scss$/,
loaders: ['raw-loader', 'sass-loader'],
});
return config;
};
And, the scss file for my component was loaded without problems
src/app/modules/ui-common/video-poster/video-poster.component.ts
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-video-poster',
templateUrl: './video-poster.component.html',
styleUrls: ['./video-poster.component.scss'] // this were loaded without problems
})
export class VideoPosterComponent implements OnInit {
private hostUrl = 'https://s3-eu-west-1.amazonaws.com/video.gallereplay.com/portfolio/clients';
private baseUrl = `${this.hostUrl}/jaegermeister/Cinemagraph_plain/1920x1080`;
#Input()
public videoUrls = {
poster: `${this.baseUrl}/cinemagraph.jpg`,
mp4: `${this.baseUrl}/cinemagraph.mp4`,
webm: `${this.baseUrl}/cinemagraph.webm`,
}
#Input() public title = 'Custom Cinemagraph Productions';
#Input() public subtitle = 'Exclusive Content for Businesses';
constructor() { }
ngOnInit() {
}
}
Repository:
https://github.com/gpincheiraa/storybook-components-sample
run npm install && npm run storybook for check storybook running.
What I am doing wrong??
I assume that, like me, you're looking for a way to load global styles from SASS files into an Angular Storybook. I know it's been a while since you asked, but I came across this solution while searching for a way to accomplish this: https://github.com/storybookjs/storybook/issues/6364#issuecomment-485651328.
Basically, you can load your global styles in the Storybook config file. However, you need to use inline webpack loaders in the import path so Storybook will load them properly.
import '!style-loader!css-loader!sass-loader!../src/styles.scss';
That did the trick for me. In the end I didn't have to bother with the custom webpack config. Hopefully that solves your problem!
You are trying to import an scss file from your typescript. You must include it from your scss.
Please remove :
//This scss it is not loaded
import '../src/styles.scss';
In your scss file add :
#import "styles.scss";
In you angular.json add :
"styles": [
"src/styles.scss",
],
"stylePreprocessorOptions": {
"includePaths": [
"src/" // maybe not required in your case
]
},
In you .storybook/webpack.config.js please try :
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
loaders: ["sass-loader"],
include: path.resolve(__dirname, "../src/")
}
]
}
};
Otherwise there is the possibility to add an alias as Xdecus said here https://github.com/storybooks/storybook/issues/3814#issuecomment-401756776
const path = require('path');
module.exports = {
resolve: {
alias: {
styles: path.resolve(__dirname, '../src/')
}
}
};
All style imports must be in Component metadata (specifically in styles or styleUrls field). You're trying to import style file as js file, which is wrong.

Categories

Resources