首页 > 解决方案 > 我的javascript文件无法识别是否有原因?

问题描述

index.js:

const { app, BrowserWindow } = require('electron');
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 400,
    height: 450,
    icon: __dirname + '/icon.png',
    title: "Password Generator",
    resizable: false,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));
  mainWindow.removeMenu()

  // Open the DevTools.
  //mainWindow.webContents.openDevTools();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

生成器.js:

const resultEl = document.getElementById('result');
const lengthEl = document.getElementById('length');
const uppercaseEl = document.getElementById('uppercase');
const lowercaseEl = document.getElementById('lowercase');
const numbersEl = document.getElementById('numbers');
const symbolsEl = document.getElementById('symbols');
const generateEl = document.getElementById('generate');
const clipboard = document.getElementById('clipboard');

const randomFunc = {
    lower: getRandomLower,
    upper: getRandomUpper,
    number: getRandomNumber,
    symbol: getRandomSymbol
}

clipboard.addEventListener('click', () => {
    const textarea = document.createElement('textarea');
    const password = resultEl.innerText;

    if(!password) { return; }

    textarea.value = password;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    textarea.remove();
});

generate.addEventListener('click', () => {
    const length = +lengthEl.value;
    const hasLower = lowercaseEl.checked;
    const hasUpper = uppercaseEl.checked;
    const hasNumber = numbersEl.checked;
    const hasSymbol = symbolsEl.checked;

    resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, length);
});

function generatePassword(lower, upper, number, symbol, length) {
    let generatedPassword = '';
    const typesCount = lower + upper + number + symbol;
    const typesArr = [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]);

    // Doesn't have a selected type
    if(typesCount === 0) {
        return '';
    }

    // create a loop
    for(let i=0; i<length; i+=typesCount) {
        typesArr.forEach(type => {
            const funcName = Object.keys(type)[0];
            generatedPassword += randomFunc[funcName]();
        });
    }

    const finalPassword = generatedPassword.slice(0, length);

    return finalPassword;
}

function getRandomLower() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}

function getRandomUpper() {
    return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}

function getRandomNumber() {
    return +String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}

function getRandomSymbol() {
    const symbols = '!@#$%^&*(){}[]=<>/,.'
    return symbols[Math.floor(Math.random() * symbols.length)];
}

索引.html:

<!DOCTYPE html>
<html>
<div class="container">
    <h2>Password Generator</h2>
    <link rel="stylesheet" href="index.css" />
    <div class="result-container">
        <span id="result"></span>
        <script src='https://kit.fontawesome.com/a076d05399.js'></script>
        <button class="btn" id="clipboard">
            <i class="far fa-clipboard"></i>
        </button>
    </div>
    <div class="settings">
        <div class="setting">
            <label>Password length</label>
            <input type="number" id="length" min='4' max='20' value='20' />
        </div>
        <div class="setting">
            <label>Include uppercase letters</label>
            <input type="checkbox" id="uppercase" checked />
        </div>
        <div class="setting">
            <label>Include lowercase letters</label>
            <input type="checkbox" id="lowercase" checked />
        </div>
        <div class="setting">
            <label>Include numbers</label>
            <input type="checkbox" id="numbers" checked />
        </div>
        <div class="setting">
            <label>Include symbols</label>
            <input type="checkbox" id="symbols" checked />
        </div>
    </div>
    <button class="btn btn-large" id="generate">
        Generate password
    </button>
</div>
<style>
  body {
    overflow-x: hidden;
  }
</style>

    <!-- You can also require other files to run in this process -->
        <script>require('/generator.js')</script>
  </body>
</html>

包.json:

{
  "name": "password-generator",
  "productName": "Password Generator",
  "version": "1.0.0",
  "description": "Password generator desktop app",
  "main": "src/index.js",
  "scripts": {
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "publish": "electron-forge publish",
    "build-installer": "electron-builder",
    "lint": "echo \"No linting configured\""
  },
  "build": {
    "appId": "password-generator"
  },
  "win": {
    "target": [
      "nsis"
    ],
    "icon": "src/icon.png"
  },
  "nsis": {
    "installerIcon": "src/icon.png",
    "uninstallerIcon": "src/icon.png",
    "uninstallDisplayName": "Password Generator",
    "oneClick": false,
    "allowToChangeInstallationDirectory": true
  },
  "keywords": [],
  "author": "JipBit",
  "license": "MIT",
  "config": {
    "forge": {
      "packagerConfig": {},
      "makers": [
        {
          "name": "@electron-forge/maker-squirrel",
          "config": {
            "name": "password_generator"
          }
        },
        {
          "name": "@electron-forge/maker-zip",
          "platforms": [
            "darwin"
          ]
        },
        {
          "name": "@electron-forge/maker-deb",
          "config": {}
        },
        {
          "name": "@electron-forge/maker-rpm",
          "config": {}
        }
      ]
    }
  },
  "dependencies": {
    "electron-squirrel-startup": "^1.0.0"
  },
  "devDependencies": {
    "@electron-forge/cli": "^6.0.0-beta.52",
    "@electron-forge/maker-deb": "^6.0.0-beta.52",
    "@electron-forge/maker-rpm": "^6.0.0-beta.52",
    "@electron-forge/maker-squirrel": "^6.0.0-beta.52",
    "@electron-forge/maker-zip": "^6.0.0-beta.52",
    "electron": "9.1.0"
  }
}

更新错误:

Uncaught Error: Cannot find module 'generator.js'
Require stack:
- C:\Users\mel\Desktop\Password Generator 1.0\password-generator\src\index.html
    at Module._resolveFilename (internal/modules/cjs/loader.js:797)
    at Function.i._resolveFilename (electron/js2c/renderer_init.js:42)
    at Module._load (internal/modules/cjs/loader.js:690)
    at Function.Module._load (electron/js2c/asar.js:769)
    at Module.require (internal/modules/cjs/loader.js:852)
    at require (internal/modules/cjs/helpers.js:74)
    at index.html:46

信息:所有这些文件都在文件夹 src 下。我试图改变路径并添加 src 但这并没有什么不同。我昨天遇到了这个问题,有人回答我的问题,告诉我在我的 HTML 文件中需要它。后来它确实成功了,但我开始了一个新项目,因为我遇到了包装问题。我现在又回到了同样的问题,并且要求 generator.js 文件并没有解决任何问题。该应用程序可以正常打开而没有错误,但是 javascript 无法正常运行并且几乎不存在。当我点击生成时,它是为了在屏幕上打印文本,但似乎什么也没有出现。我目前正在使用 GitHub 的电子框架。任何反馈表示赞赏。

标签: javascripthtmlnpmelectron

解决方案


推荐阅读