【问题标题】:Trying to load large json files using file-loader and webpack尝试使用文件加载器和 webpack 加载大型 json 文件
【发布时间】:2018-10-18 16:09:43
【问题描述】:

我一直在尝试几种方法来使用 Webpack (v4.3) 在我的 React 应用程序中加载我需要的大型 json (> 144 MB) 文件。我在关注GitHub Issue on Webpack 并尝试使用带有 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]"
						}
					}
				]
			}

		]
	},
};

【问题讨论】:

  • file-loader 确实为您提供了输出文件夹中文件的路径。这就是为什么使用非 js 资产(例如图像)很有用的原因(通常你不想将图像捆绑到你的 js 文件中)。你也不想捆绑 140M 的 json 数据文件。因此,您需要使用 fetch 和来自加载程序的 url 手动加载 json 文件。另外,我建议您以某种方式重组数据。一次加载 140Mb 数据听起来是个坏主意。
  • 感谢 @YuryTarabanko 现在将数据移动到 Elastic Search,感谢您的回答。

标签: json reactjs webpack webpack-file-loader


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-12-09
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多