json - 尝试使用文件加载器和 webpack 加载大型 json 文件
问题描述
我一直在尝试几种方法来使用 Webpack (v4.3) 在我的 React 应用程序中加载我需要的大型 json (> 144 MB) 文件。我在 Webpack 上关注 GitHub 问题, 并尝试使用带有 Webpack 的文件加载器。PFB,webpack.config.js 文件。
当我尝试调试值时,const ORIGIN_DESTINATION_DATA = require('../.././data/./origin_destination.json');
我看到 ORIGIN_DESTINATION_DATA 包含“src/data/destination_origin.json”字符串而不是实际的 json 数据。
var webpack = require('webpack');
var path = require('path');
const flaskApp = path.join(__dirname, '../', 'app_name');
module.exports = {
entry: __dirname + '/src/index.jsx',
output: {
path: flaskApp + '/static',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.json']
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.less$/,
loaders: ["style-loader", "css-loader", "less-loader"]
}, {
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
}, {
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}, {
test: /\.geojson$/,
loader: 'url-loader?limit=100000'
}, {
type: 'javascript/auto',
test: /\.json$/,
use: [{
loader: 'file-loader',
options: {
name: "[path][name].[ext]"
}
}
]
}
]
},
};
解决方案
您可以使用 copyWebpackPlugin:https ://webpack.js.org/plugins/copy-webpack-plugin/
它基本上将您的文件或文件夹从 a 复制到 b
在 webpack.config 中:
const CopyPlugin = require("copy-webpack-plugin");
...
plugins: [
new CopyPlugin([
{
from: path.resolve(__dirname, "src/pathTo/giantJsonFolder"),
to: "assets",
},
]),
],
然后在需要的地方获取它:
const response = await fetch('assets/filename.json')
const json = await response.json();
console.log(json)
推荐阅读
- c++ - 在对象未更新时传递对常量对象的引用
- javascript - 更改事件在两个元素中不起作用
- python - 我想用这段代码生成随机数,但它会产生错误
- python - file_version_info.txt中的filevers/prodvers这四项是什么意思?
- android - 我如何实现这个设计?
- for-loop - 在创建活动之前检查日历是否有重复项
- sass - 当页面重新加载时,Gulp watch with Livereload 重新加载,或者自己
- ansible - 使用 jinja2 的 ansible 库存组
- reactjs - 选择时 React Native TextInput 缩小,我该如何停止它?
- java - 在 Quarkus-Camel 中的任何其他类之前调用一个类