twstyled / electron-vite-react

🔰 This Starter utilizes Electron, TypeScript, Vite, React, Tailwind CSS with twstyled CSS in JS. It tries to adhere best practices.
MIT License
93 stars 20 forks source link

Bad alias resolution when the main process references the common folder #1

Open zerokarafont opened 3 years ago

zerokarafont commented 3 years ago

I'm sorry I'm not a native English speaker. This is my problem When I tried to reference the common configuration, I couldn't find the correct path in the packed dist directory, It seems that my configuration is not bundled correctly

import { app, BrowserWindow, Tray, Menu } from 'electron'
import type { BrowserWindowConstructorOptions } from 'electron'
import windowStateKeeper from 'electron-window-state'
import config from '@/common/config'

index.js in dist directory

var import_electron = __toModule(require("electron"));
var import_electron_window_state = __toModule(require("electron-window-state"));
var import_config = __toModule(require("@/common/config"));
...

error stack

Error: Cannot find module '@/common/config'
Require stack:
- F:\code\project\electron-vite-react\dist\index.js
- F:\code\project\electron-vite-react\node_modules\electron\dist\resources\default_app.asar\main.js
-
    at Module._resolveFilename (internal/modules/cjs/loader.js:887:15)
    at Function.n._resolveFilename (electron/js2c/browser_init.js:261:1128)
    at Module._load (internal/modules/cjs/loader.js:732:27)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12684)
    at Module.require (internal/modules/cjs/loader.js:959:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (F:\code\project\electron-vite-react\dist\index.js:22:32)
    at Module._compile (internal/modules/cjs/loader.js:1078:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108:10)
    at Module.load (internal/modules/cjs/loader.js:935:32)

tree

├─.config
├─.vscode
├─public
├─scripts
└─src
    ├─common
    │  ├─config
    │  └─event
    ├─main
    │  ├─ipc
    │  └─work_thread
    └─renderer
        ├─components
        │  ├─DropZone
        │  └─HtmlHead
        ├─layouts
        └─pages
            └─home

how can i fix it ?

jdamon96 commented 3 years ago

I'm also having this same issue.

So far in my research it appears that you may be able to fix this by using an esbuild plugin to change the import's path during the build process - see the discussion here: https://github.com/evanw/esbuild/issues/456

devjayprakash commented 3 years ago

i am also facing the same issue... does anyone has some solution

zerokarafont commented 3 years ago

@jdamon96 @DevelopAppWithMe esbuild alias plugin not work for me. My solution is not to use esbuild, the main process uses tsc to compile. Here is the key script (from another scaffold, however i forget where is it from, shoud be in awesome-vite repo ) you should replace original main compile script with this. Everything is perfect except that it is a little slower than esbuild.


import type {
  CompilerOptions,
  Diagnostic,
  FormatDiagnosticsHost,
} from "typescript";
import * as ts from "ttypescript";
import * as path from "path";
import * as os from "os";
import { CompileError, WatchMain, outDirMain, mainPath } from "./common";

let diagnosticErrors: Array<CompileError> = [];

const formatHost: FormatDiagnosticsHost = {
  getCanonicalFileName: (filepath) => filepath,
  getCurrentDirectory: ts.sys.getCurrentDirectory,
  getNewLine: () => ts.sys.newLine,
};

function reportDiagnostic(diagnostic: Diagnostic) {
  if (!diagnostic.file || !diagnostic.start || !diagnostic.length) {
    return;
  }

  const diagnosticMessage = ts.flattenDiagnosticMessageText(
    diagnostic.messageText,
    formatHost.getNewLine()
  );
  const filepath = diagnostic.file.fileName.replace(process.cwd(), "");
  const { start } = diagnostic;
  const len = diagnostic.length;

  const linesOfCode = diagnostic.file.text.split(os.EOL);
  const line = diagnostic.file.text.substr(0, start + 1).split(os.EOL).length;
  const lineStart =
    diagnostic.file.text.substring(0, start + 1).lastIndexOf(os.EOL) + 1;
  const col = start - lineStart;

  const compileError: CompileError = {
    location: {
      column: col,
      file: filepath,
      length: len,
      line,
      lineText: linesOfCode[line - 1],
    },
    message: diagnosticMessage,
  };
  diagnosticErrors.push(compileError);
}

export const watchMain: WatchMain = (
  reportError,
  buildStart,
  buildComplete,
  notFoundTSConfig
) => {
  const configPath = path.join(mainPath, "tsconfig.json");
  if (!configPath) {
    notFoundTSConfig();
  }

  const createProgram = ts.createSemanticDiagnosticsBuilderProgram;

  const host = ts.createWatchCompilerHost(
    configPath,
    {
      sourceMap: true,
    },
    ts.sys,
    createProgram,
    reportDiagnostic,
    (
      diagnostic: Diagnostic,
      _: unknown,
      options: CompilerOptions,
      errorCount?: number
    ) => {
      if (!!errorCount && errorCount > 0) {
        reportError(diagnosticErrors);
        diagnosticErrors = [];
      } else if (diagnostic.code === 6194) {
        buildComplete(outDirMain);
      } else if (diagnostic.code === 6032 || diagnostic.code === 6031) {
        buildStart();
      }
    }
  );

  ts.createWatchProgram(host);
};
=== tsconfig ===
{
"paths": {
      "@main/*": [
        "main/*"
      ],
      "@renderer/*": [
        "renderer/*"
      ],
      "@common/*": [
        "common/*"
      ],
    },
}```
anup-a commented 3 years ago

Did anyone fix this using esbuild ? It wasn't able to work with relative paths neither aliases. This seems to be major flaw @guybarnard .

lewisandrew commented 3 years ago

Likewise, I get the same error for aliases and for relative paths, i.e. './coolStuff'

fursandy commented 2 years ago

@anup-a I have fix this using "esbuild-node-externals" and set bundle true

import { nodeExternalsPlugin } from "esbuild-node-externals";

esbuild.build({
  ...
  plugins: [nodeExternalsPlugin()],
  bundle: true
  ...
});