枣庄手机网站开发公司,专业网站建设加工,制作网站副本,上海网站改版背景
electron 主渲进程的打包#xff0c;以及 preload 的打包#xff0c;还有注入脚本的打包#xff0c;这些东西 webpack 本身是自带的#xff0c;这里主要讲一下 target: node 模式 代码
https://gitee.com/sen2020/webpack-demo/tree/feature%2Fnode-code-package/ n…背景
electron 主渲进程的打包以及 preload 的打包还有注入脚本的打包这些东西 webpack 本身是自带的这里主要讲一下 target: node 模式 代码
https://gitee.com/sen2020/webpack-demo/tree/feature%2Fnode-code-package/ node 模式 平时打包都是 web 模式web 模式必须由 web 服务输出到浏览器来渲染 而 webpack 可以面向多种打包模式其中针对 electron 就给出了三种 electron-mainelectron-rendererelectron-preload同时针对 node给出了两种一种是 node一种是 node-async后者适用于模块化的服务例如有插件模块的 node 框架。 node 模式打包注意点
其中 node 这里给的__dirname 意思是不让替换的意思否则会按照相对路径 / 进行转换
// 设置目标环境为 Node.js
target: node,
node: {__dirname: false,__filename: false,
},
webpack 打包默认是 commonJS 规则
ES6 的模式 export {a} 变量后使用者如果 a则模块中的 a 也会加
而 CommonJS 模式 import {a}则是拷贝一份 aa不影响 export {a} 模块中的 a 的值这里要特别注意
文件存储引发容易忽略的导出案例
// config.js
{a: 1
}// moduleA.js
const fs require(fs);
const path require(path);const configPath path.join(__dirname, config.json);// 读取配置文件中的 a 值
function readConfig() {const data fs.readFileSync(configPath, utf8);const config JSON.parse(data);return config.a;
}// 将新的 a 值写入配置文件
function writeConfig(aValue) {const config {a: aValue};fs.writeFileSync(configPath, JSON.stringify(config, null, 2), utf8);
}let a readConfig();function increment() {writeConfig(2);
}function func() {return new Promise((resolve) {increment();resolve();});
}function func2() {console.log(func2 a value:, a)// 这里拿到的是初次从config.json获取到的若想获取修改要重新从文件中提取return a;
}module.exports {a, func, func2};index.js 文件内容
import {func, func2} from ./moduleAfunc().then(() {console.log(func2());
});//init get config.a: 1
//func2 a value: 1
//1