简体   繁体   English

减少 Webpack 包中的 JSON 文件大小

[英]Reducing a JSON file size in Webpack bundle

I am trying to optimise my Webpack bundle and I have identified a large chunk of data that is being bundled from one of my dependencies.我正在尝试优化我的 Webpack 包,并且我已经确定了从我的一个依赖项中捆绑的大量数据。 The dependency is world-countries , which is just a huge JSON array of objects containing country data.依赖项是world-countries ,它只是一个包含国家数据的大型 JSON 对象数组。 I am however only using a fraction of this data in my app (a simple React app).然而,我只在我的应用程序(一个简单的 React 应用程序)中使用了这些数据的一小部分。

So what I am thinking is that I want to add something into my Webpack config that will effectively let me map the large objects down into just the properties I am using, and avoid having all the rest of the data end up in my bundle.所以我在想的是我想在我的 Webpack 配置中添加一些东西,这将有效地让我 map 将大对象归结为我正在使用的属性,并避免将所有 Z65E8800B5C6800AAD896F888 的数据放在我的包中。

My only idea currently on how to do this would be to write a node script that runs postinstall or prebuild that imports the module, maps it and saves it back out to disk in a new JSON file.我目前关于如何做到这一点的唯一想法是编写一个运行 postinstall 或 prebuild 的节点脚本来导入模块,将其映射并在新的 JSON 文件中将其保存回磁盘。 Then that JSON file is what my app imports.然后那个 JSON 文件就是我的应用程序导入的文件。

I'm looking for any advice or ideas on the best way to implement this, preferably in a way that doesn't affect my apps code and is just part of the Webpack config.我正在寻找有关实现此功能的最佳方法的任何建议或想法,最好以不影响我的应用程序代码且只是 Webpack 配置的一部分的方式。

You can write a custom loader which will be applied on the Jason import, inside it filter out what you need.您可以编写一个自定义加载器,该加载器将应用于 Jason 导入,在其中过滤掉您需要的内容。

i am using DefinePlugin now to create only the JSON I need.我现在使用DefinePlugin来创建我需要的 JSON。 In my example i am using the countries from country-data :在我的示例中,我使用的是country-data中的国家/地区:

Webpack config: Webpack 配置:

import { countries } from 'country-data';

...

plugins: [
  new webpack.DefinePlugin({
    COUNTRIES: webpack.DefinePlugin.runtimeValue(function() {
      return JSON.stringify(countries.all.filter(function (c) {
        // Has "United Kingdom" twice, @see https://github.com/OpenBookPrices/country-data/issues/72
        var assigned = c.status === 'assigned';
        // cleanup JSON
        ['countryCallingCodes', 'languages', 'currencies', 'emoji', 'ioc', 'alpha3', 'status'].forEach(function (key) {
          delete c[key];
        });
        return assigned;
      }));
    }),
  }),
]

You then can use COUNTRIES in your code!然后,您可以在代码中使用COUNTRIES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM