首页 > 解决方案 > 尝试使用文件加载器和 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]"
						}
					}
				]
			}

		]
	},
};

标签: jsonreactjswebpackwebpack-file-loader

解决方案


您可以使用 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)

推荐阅读