自学内容网 自学内容网

webpack 的打包target讲解 & node环境打包下的文件存储造成不易察觉的坑点

背景

electron 主渲进程的打包,以及 preload 的打包,还有注入脚本的打包,这些东西 webpack 本身是自带的,这里主要讲一下 target: node 模式

代码

https://gitee.com/sen2020/webpack-demo/tree/feature%2Fnode-code-package/

node 模式

  1. 平时打包都是 web 模式,web 模式必须由 web 服务输出到浏览器来渲染, 而 webpack 可以面向多种打包模式,其中针对 electron 就给出了三种 electron-main,electron-renderer,electron-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},则是拷贝一份 a,a++不影响 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 "./moduleA"

func().then(() => {
    console.log(func2());
});

//init get config.a: 1
//func2 a value: 1
//1


原文地址:https://blog.csdn.net/wangsenling/article/details/142535056

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!