Webpack环境下无法用fs读写JSON文件,求替代实现方案
Webpack环境下读写JSON文件的替代方案
一、前端侧存储(仅在浏览器内持久化)
如果数据不需要同步到服务器或本地磁盘文件,仅在浏览器端保存使用,可选择以下方案:
1. localStorage / sessionStorage
适合存储小体积JSON数据,操作简单:
// 保存数据到localStorage const data = [{ id: 1, name: "test" }, { id: 2, name: "demo" }]; localStorage.setItem('panelData', JSON.stringify(data)); // 读取数据 const savedData = JSON.parse(localStorage.getItem('panelData')) || [];
注意:localStorage存储上限约5MB,数据会永久保留在浏览器(除非手动清除);sessionStorage仅在当前浏览器会话有效。
2. IndexedDB
适合存储大量数据,支持异步操作:
// 简单封装的IndexedDB保存方法 function saveDataToIndexedDB(data) { return new Promise((resolve, reject) => { const request = indexedDB.open('PanelDB', 1); request.onupgradeneeded = (event) => { const db = event.target.result; db.createObjectStore('dataStore', { keyPath: 'id' }); }; request.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction('dataStore', 'readwrite'); const store = transaction.objectStore('dataStore'); data.forEach(item => store.put(item)); transaction.oncomplete = () => { db.close(); resolve(); }; transaction.onerror = (err) => reject(err); }; request.onerror = (err) => reject(err); }); } // 使用示例 const data = [{ id: 1, name: "test" }, { id: 2, name: "demo" }]; saveDataToIndexedDB(data).then(() => console.log('数据保存成功'));
二、通过后端接口实现文件读写(需Node.js后端配合)
浏览器无直接操作本地磁盘文件的权限,若必须将数据写入本地JSON文件,需通过后端接口中转:
1. 搭建简单Node.js后端(Express示例)
// server.js const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); app.use(express.json()); // 接收前端数据并写入JSON文件 app.post('/save-data', (req, res) => { const data = req.body; const filePath = path.join(__dirname, 'data.json'); fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => { if (err) { return res.status(500).json({ success: false, message: '写入失败' }); } res.json({ success: true, message: '数据保存成功' }); }); }); // 读取JSON文件接口 app.get('/get-data', (req, res) => { const filePath = path.join(__dirname, 'data.json'); fs.readFile(filePath, 'utf8', (err, data) => { if (err) { return res.status(500).json({ success: false, message: '读取失败' }); } res.json({ success: true, data: JSON.parse(data) }); }); }); app.listen(3000, () => console.log('后端服务运行在http://localhost:3000'));
2. 前端发送请求(fetch示例)
// 保存数据 const data = [{ id: 1, name: "test" }, { id: 2, name: "demo" }]; fetch('http://localhost:3000/save-data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(res => res.json()) .then(result => console.log(result.message)); // 读取数据 fetch('http://localhost:3000/get-data') .then(res => res.json()) .then(result => console.log(result.data));
三、Webpack构建阶段生成JSON文件(仅构建时操作)
若需求是在Webpack构建过程中生成/修改JSON文件(而非运行时),可使用自定义插件或现成插件:
1. 自定义Webpack插件
// webpack.config.js const fs = require('fs'); const path = require('path'); class GenerateJsonPlugin { constructor(options) { this.options = options; } apply(compiler) { // 构建完成后写入文件 compiler.hooks.done.tap('GenerateJsonPlugin', () => { const filePath = path.join(compiler.outputPath, this.options.filename); fs.writeFileSync(filePath, JSON.stringify(this.options.data, null, 2)); }); } } module.exports = { // ...其他Webpack配置 plugins: [ new GenerateJsonPlugin({ filename: 'data.json', data: [{ id: 1, name: "test" }, { id: 2, name: "demo" }] }) ] };
2. 使用现成插件(如copy-webpack-plugin)
复制并修改已有JSON模板:
// webpack.config.js const CopyPlugin = require('copy-webpack-plugin'); const fs = require('fs'); module.exports = { // ...其他配置 plugins: [ new CopyPlugin({ patterns: [ { from: 'src/data-template.json', to: 'data.json', transform(content) { const templateData = JSON.parse(content.toString()); // 修改模板数据 templateData.items = [{ id: 1, name: "test" }, { id: 2, name: "demo" }]; return JSON.stringify(templateData, null, 2); }, }, ], }), ], };
内容的提问来源于stack exchange,提问作者Preem Palver2
相关产品推荐
相关产品推荐

