You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron JS:如何在renderer.js中导入自定义JS文件及解决导入语法错误

在Electron的renderer.js中正确导入自定义JS文件的解决方案

嘿,这个问题我之前踩过坑!你碰到的Uncaught SyntaxError: Cannot use import statement outside a module报错,本质是因为Electron默认把renderer进程的脚本当作普通浏览器脚本,而非ES模块。下面给你几个实用的解决办法,按需选择:

方法1:将renderer脚本标记为ES模块

这是最贴近浏览器原生ES模块的方式,步骤很简单:

  • 打开加载renderer.js的HTML文件,把原来的script标签加上type="module"属性:
    <!-- 原来的写法 -->
    <script src="./renderer.js"></script>
    <!-- 修改后 -->
    <script type="module" src="./renderer.js"></script>
    
  • 确保你的math.js是ES模块格式,用export导出内容:
    // math.js
    export const add = (a, b) => a + b;
    export const multiply = (a, b) => a * b;
    
  • 保持renderer.js里的import语法不变:
    // renderer.js
    import * as math from './math.js';
    console.log(math.add(2, 3)); // 输出5
    

注意:ES模块的相对路径必须完整,不能省略./,否则会报错。

方法2:使用CommonJS的require语法(适合快速开发/内部应用)

如果你的项目更偏向Node.js风格,可以用CommonJS规范,但要注意Electron的安全配置:

  1. 在主进程的main.js中,修改BrowserWindow的webPreferences配置,开启node集成并关闭上下文隔离(注意:此方法安全性较低,不建议用于面向外部的应用):
    // main.js
    const { BrowserWindow } = require('electron');
    const path = require('path');
    
    function createWindow() {
      const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: false
        }
      });
      mainWindow.loadFile('index.html');
    }
    
  2. 修改math.js为CommonJS导出格式:
    // math.js
    module.exports = {
      add: (a, b) => a + b,
      multiply: (a, b) => a * b
    };
    
  3. 在renderer.js中用require导入:
    // renderer.js
    const math = require('./math.js');
    console.log(math.multiply(2, 3)); // 输出6
    

方法3:使用Preload脚本(官方推荐,安全规范)

现代Electron推荐使用上下文隔离(contextIsolation)来保障应用安全,此时可以通过preload脚本作为桥梁,把自定义模块的方法暴露给renderer进程:

  1. 在main.js中配置preload路径(默认已开启contextIsolation,无需额外关闭):
    // main.js
    const { BrowserWindow } = require('electron');
    const path = require('path');
    
    function createWindow() {
      const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          preload: path.join(__dirname, 'preload.js')
        }
      });
      mainWindow.loadFile('index.html');
    }
    
  2. 编写preload.js,用contextBridge暴露自定义模块的方法:
    // preload.js
    const { contextBridge } = require('electron');
    const math = require('./math.js'); // 这里可以用CommonJS导入
    
    // 向renderer进程暴露名为electronMath的全局对象
    contextBridge.exposeInMainWorld('electronMath', {
      add: math.add,
      multiply: math.multiply
    });
    
  3. 在renderer.js中直接调用全局对象的方法:
    // renderer.js
    console.log(window.electronMath.add(2, 3)); // 输出5
    

这个方法既遵循了Electron的安全规范,又能优雅地使用自定义模块,是生产环境的首选。

内容的提问来源于stack exchange,提问作者user3324131

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:32:35