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的安全配置:
- 在主进程的
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'); } - 修改
math.js为CommonJS导出格式:// math.js module.exports = { add: (a, b) => a + b, multiply: (a, b) => a * b }; - 在
renderer.js中用require导入:// renderer.js const math = require('./math.js'); console.log(math.multiply(2, 3)); // 输出6
方法3:使用Preload脚本(官方推荐,安全规范)
现代Electron推荐使用上下文隔离(contextIsolation)来保障应用安全,此时可以通过preload脚本作为桥梁,把自定义模块的方法暴露给renderer进程:
- 在
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'); } - 编写
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 }); - 在
renderer.js中直接调用全局对象的方法:// renderer.js console.log(window.electronMath.add(2, 3)); // 输出5
这个方法既遵循了Electron的安全规范,又能优雅地使用自定义模块,是生产环境的首选。
内容的提问来源于stack exchange,提问作者user3324131
相关产品推荐
相关产品推荐

