Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - 如何对需要多个图像(URL和文件加载器)的资产对象进行树状握手(How to treeshake asset object that requires multiple images (url and file loader))

I've got 1 js file that exports requires to certain images in following manner:

(我有1 js文件以以下方式导出到某些图像:)

export const assets = {
  UI: {
    BUTTON_GREEN: require('../assets/minified/ui/button_green_background.png'),
    BUTTON_YELLOW: require('../assets/minified/ui/button_yellow_background.png'),
  },
  BACKGROUNDS: {
    BACKGROUND_FIRE: require('../assets/minified/bg/background_fire.jpg'),
  }
};
/* etc... */

I then use this in various pages as follows

(然后,我在各个页面中如下使用)

import {assets} from "./assets.js"

<img src={assets.UI.BUTTON_GREEN} />

I do this as it is easier to import images when using typescript due to autocomplete.

(我这样做是因为由于自动完成功能,在使用打字稿时更容易导入图像。)

I then have following loaders in my webpack config

(然后我的webpack配置中有以下加载程序)

  {
    test: //ui/[^.]+.(png|jpe?g|svg)$/,
    loader: 'url-loader',
    options: {
      name: 'static/images/[name]-[hash].[ext]',
      limit: 50000,
      esModule: false
    }
  },
  {
    test: //bg/[^.]+.(png|jpe?g|svg)$/,
    loader: 'file-loader',
    options: {
      name: 'static/images/[name]-[hash].[ext]',
      esModule: false
    }
  }

I use separate loaders in order to inline ui elements and parse other bigger images as normal files.

(我使用单独的加载程序以内联ui元素并将其他较大的图像解析为普通文件。)

I set esModule to false because otherwise I am not able to get my requires working for some reason, as they return 'default' instead of string related to image.

(我将esModule设置为false因为否则由于某些原因我将无法满足我的要求,因为它们返回“默认”而不是与图像相关的字符串。)

I then have my pages split into their own js chunks ie

(然后,我将页面分成自己的js块,即)

Page                        Size
┌ * /                       74 kB
├   /_app                   1.25 MB
├   /_document
├   /_error                 9.43 kB
├ * /registration/sign-in  697 B
└ * /registration/sign-up    438 B

but as you can see my _app got over 1mb, this is due to me inlining some ui images and they are all spit into this one file, even though it uses just 2 images.

(但正如您所见,我的_app超过1mb,这是由于我内联了一些ui图像,尽管它们仅使用了2张图像,但它们都被吐入了这个文件。)

So my question is: how can I restructure my approach in order to only add inlined image data to js chunks of pages that use it?

(所以我的问题是:我如何重组我的方法,以便仅将内联图像数据添加到使用该图像数据的js块中?)

I am open to additional loader settings / restructuring my asset file etc...

(我愿意接受其他加载程序设置/重组我的资产文件等...)

  ask by Ilja translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...