TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".vue" when run node in ssr.js - node.js

I use Inertia, Vue3, and Vite as bundling assets. When I set up and run with SSR in nodejs the error always appears Unknown file extension ".vue". I've been googling for days but haven't solved it.
This is my ssr.js file which I run with nodemon
import { createSSRApp, h } from 'vue'
import { renderToString } from '#vue/server-renderer'
import { createInertiaApp } from '#inertiajs/inertia-vue3'
import createServer from '#inertiajs/server'
createServer.default((page) => createInertiaApp({
page,
render: renderToString,
resolve: async (name) => {
return (await import(`./Pages/${name}.vue`)).default;
},
setup({ app, props, plugin }) {
return createSSRApp({
render: () => h(app, props),
}).use(plugin)
},
}))
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
// import react from '#vitejs/plugin-react';
import vue from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
ssr: 'resources/js/ssr.mjs',
}),
// react(),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
ssr: {
noExternal: ['#inertiajs/server'],
},
resolve: {
alias: {
'#': '/resources/js'
}
}
});
when I run it with nodemon ssr.js an error like this will appear
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".vue" for C:\Users\USER\Documents\biviplant\biviplant\resources\js\Pages\Test.vue

Related

Jest environment has been torn down error in graphql, nodejs project. Used jest.useFakeTimers but still getting the error

Getting ReferenceError: You are trying to import a file after the Jest environment has been torn down From office/test/office.test.ts.
Used jest.useFakeTimers(); after imports, but the issue still exists. Is there any way to resolve it ?
Here is my jest.config.ts
import type { Config } from "#jest/types"
const config: Config.InitialOptions = {
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
moduleFileExtensions: [ 'js','ts'],
testEnvironment: "jest-environment-node",
fakeTimers: {
enableGlobally: true,
},
verbose: true
}
export default config
The test file office.test.ts
import {ApolloServer} from 'apollo-server'
import {expect,test,jest} from '#jest/globals';
import officeGql from '../controllers/controller'
jest.useFakeTimers();
test('Office Module Test', async () => {
let typeDefs = officeGql.types
let resolvers = officeGql.resolvers
let testServer = new ApolloServer({
typeDefs,
resolvers,
});
const response = await testServer.executeOperation({
query: `query offices(limit: $limit,offset: $offset){name, address}`,
variables: { limit: 10,offset:0 },
});
expect(response.data).toBeTruthy();
});

Disable hash in vite script - multiple entry points for chrome extension

I'm trying to write a chrome extension. I've found a way to create multiple
pages and a background script, but the background script contains a hash and is
placed into the dist/assets folder. I would like to output just 'dist/background.js'. Alternatively (and maybe better) I would like to have my manifest updated to contain the actual script name with the hash.
Here's my vite.config.ts
import { defineConfig, BuildOptions } from 'vite'
import vue from '#vitejs/plugin-vue'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
// lib: {
// entry: resolve(__dirname, 'background.ts'),
// name: 'background',
// fileName: format => `background.{format}.js`
// },
rollupOptions: {
// output: {
// format: 'cjs'
// },
input: {
main: resolve(__dirname, 'index.html'),
popup: resolve(__dirname, 'popup/index.html'),
options: resolve(__dirname, 'options/index.html'),
background: resolve(__dirname, 'background.ts'),
},
// output: {
// format: 'cjs'
// }
}
}
})
I've tried a few things and some are shown here commented out, but I couldn't get anything to work how I wanted. Finally I was able to get it to work if I create a separate vite.config.background.ts file:
import { defineConfig } from 'vite'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
build: {
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, 'background.ts'),
output: {
format: "esm",
file: "dist/background.js",
dir: null,
}
}
}
})
And edit my build script to build it after the other config:
"build": "vue-tsc --noEmit && vite build && vite build --config vite.config.background.ts",
But is there any way to use just one file, or to generate the manifest and use the hashed
file name? Right now it is a static json file.
This is what I ended up doing which isn't optimal. It's just hard to believe that you can specify multiple inputs which produce multiple outputs, but not define output settings for each... Structure:
+-- dist (output directory)
+-- options (options page)
+-- popup (popup page)
+-- public (contents copied directly to dist
| +-- background.js (generated background script from '/background.ts')
| +-- manifest.json (extension manifest)
+-- scripts (scripts used in build)
| +-- watch.mjs (script for 'yarn watch')
+-- src (main page)
+-- background.ts
So manifest.json is in the public directory which is copied to the root of dist. And the background script build puts the output background.js in that folder too for the main build to copy as part of the 'main' page.
scripts/watch.mjs
import { createServer, build } from 'vite'
/**
* #type {(server: import('vite').ViteDevServer) => Promise<import('rollup').RollupWatcher>}
*/
function watchBackground(server) {
return build({
configFile: 'vite.config.background.ts',
mode: 'development',
build: {
watch: {},
},
})
}
/**
* #type {(server: import('vite').ViteDevServer) => Promise<import('rollup').RollupWatcher>}
*/
function watchMain(server) {
return build({
configFile: 'vite.config.ts',
mode: 'development',
build: {
watch: {},
},
})
}
// bootstrap
const server = await createServer({ configFile: 'vite.config.ts' })
await server.listen()
await watchBackground(server) // outputs to public/background.js, so run first
await watchMain(server)
vite.config.background.ts
import { defineConfig } from 'vite'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
build: {
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, 'background.ts'),
output: {
format: "esm",
file: "public/background.js",
dir: null,
}
}
}
})
vite.config.ts
import { defineConfig, BuildOptions } from 'vite'
import vue from '#vitejs/plugin-vue'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
popup: resolve(__dirname, 'popup/index.html'),
options: resolve(__dirname, 'options/index.html'),
},
}
}
})
Running multiple rollup builds with one vite build command is not supported but you can generate a manifest file directly from vite. To generate it simply set build.manifest to true (but I am not sure if this will contain everything that you need for a manifest file for a web plugin though).

Unable to get jest to load a module (pdf.js) in a component test

I am building tests using jest that makes use of the pdf.js node library, but keep getting the following error due to jest not picking up the library properly
TypeError: Cannot set property 'workerSrc' of undefined
Here is pdfParser.js:
import * as pdfJs from 'pdfjs-dist/legacy/build/pdf'
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
pdfJs.GlobalWorkerOptions.workerSrc = pdfjsWorker
export const readPdf = async theFile => {
... (*it doesn't even get this far)
}
Here is my test (pdfParser.test.js):
import { readPdf } from '../../../../src/utils/pdfParser.js'
describe('PDF Parser', () => {
it('returns error when no file submitted', () => {
expect(1).toEqual(1)
})
})
I've tried setting the following in package.json
"jest": {
"moduleNameMapper": {
"pdfjs-dist": "<rootDir>/node_modules/pdfjs-dist/legacy/build/pdf.js"
},
"moduleDirectories": [
".",
"src",
"src/util",
"node_modules"
]
What am I doing wrong?

How to import electron in angular 5

I am trying to import electron for printing the invoice from my app
using
import { BrowserWindow } from 'electron'
But it is throwing the error.
fs.existsSync is not a function
Also, I have tried to require it from the index.html page like
<script>
var electron = require('electron');
</script>
but getting
require is not defined
The best solution I've found so far is to use ngx-electron
In your electron simply do:
const { ipcMain } = require('electron');
ipcMain.on('ping', (event, arg) => {
console.log('RECEIVED PING FROM ANGULAR APP', event, arg);
event.sender.sendSync('pong', 'yeah yeah yeah');
});
In your angular app:
import { NgxElectronModule } from 'ngx-electron';
#NgModule({
declarations: [AppComponent],
imports: [
...
NgxElectronModule
],
...
})
And inside your component:
import { ElectronService } from 'ngx-electron';
...
constructor(private _electronService: ElectronService)
...
if (this._electronService.isElectronApp) {
this._electronService.ipcRenderer.on('pong', (event, arg) => {
console.log(
'RECEIVED RESPONSE FROM ELECTRON TO ANGULAR APP',
event,
arg
);
});
}
...
this._electronService.ipcRenderer.send(
'ping',
'wow wow wow'
);

Rollup can't see named export from commonjs module

I have a simple AWS Lambda function (state-info.ts) which I am tree-shaking with Rollup and it is giving me the following error:
[!] Error: 'DB' is not exported by ../../forest-fire/abstracted-admin/lib/index.js
https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module
src/state-info.ts (10:9)
8: import { Lambda } from "aws-sdk";
9: import { STATES } from "./models/shared";
10: import { DB } from "abstracted-admin";
^
11: import { StateInfo } from "./models/StateInfo";
12: import { IApiResponse } from "./shared/ApiRetriever";
Now it just so happens that I wrote the module abstracted-admin (currently at v0.6.5 on npm) which it is complaining about and it DOES export DB as a named export (and as the default export). But for some reason Rollup is unhappy.
I've created a video walk-through of everything for full context: video.
For those of you who don't like video, here are the key facts/files:
abstracted-admin/lib/index.d.ts:
import { DB } from "./db";
export default DB;
export { DB, IFirebaseConfig, IFirebaseListener } from "./db";
abstracted-admin/lib/index.js:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const db_1 = require("./db");
exports.default = db_1.DB;
var db_2 = require("./db");
exports.DB = db_2.DB;
and from within the abstracted-admin/package.json:
{
...
"files": ["lib"],
"main": "lib/index.js",
"typings": "lib/index.d.ts",
}
state-info.ts (aka, the file being rolled up):
import {
IDictionary,
AWSGatewayCallback,
IAWSGatewayRequest,
IAWSGatewayResponse
} from "common-types";
import GetStateInfo from "./vote-smart/get-state-info";
import { Lambda } from "aws-sdk";
import { STATES } from "./models/shared";
import { DB } from "abstracted-admin";
import { StateInfo } from "./models/StateInfo";
import { IApiResponse } from "./shared/ApiRetriever";
/** ... */
Meanwhile my rollup config is:
import cjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import json from "rollup-plugin-json";
import ts from "rollup-plugin-typescript2";
import globals from "rollup-plugin-node-globals";
export default {
input: "src/state-info.ts",
output: {
file: "lib/state-info-rolled.js",
format: "cjs"
},
external: ["aws-sdk"],
plugins: [
globals(),
json(),
cjs({
include: "node_modules/**",
exclude: ["node_modules/aws-sdk/**"]
}),
ts(),
resolve({
jsnext: true,
main: true,
browser: false,
preferBuiltins: false,
extensions: [".js", ".json"]
})
]
};
I believe Rollup expects the below in this situation:
import admin from "abstracted-admin";
const { DB } = admin;
It's different from Webpack's behavior and has caught me a few times.

Resources