Webpack动态创建一个模块

Webpack动态创建一个模块

本文介绍了Webpack动态创建一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个创建SVG精灵的插件。它遍布目录,在一个图像中合并SVG文件并返回结果。我们的想法是动态创建一个模块(包含合并的图像),以便其他模块可以将其作为常用模块。或者你可以建议一个更优雅的解决方案?

I am writing a plugin which creates a SVG sprite. It globs over the directories, merge SVG files in one image and returns the result. The idea is to dynamically create a module (which contains merged images) so that other modules can require it as an usual module. Or maybe you can suggest a more elegant solution?

配置

{
  plugins: [
    new SvgSpritePlugin({
      sprites: {
        icons: 'images/svg/icons/*.svg',
        logos: 'images/svg/logos/*.svg',
        socials: 'images/svg/logos/{twitter,youtube,facebook}.svg',
      }
    })
  ]
}

应用程序中的某个地方

var logosSprite = require('sprite/logos'); // require dynamically created module
document.body.appendChild(logoSprite);


推荐答案

试着看一下外部模块和委托模块是怎样的在Webpack中提供。一个好的起点是或。

Try taking a look at how external and delegated modules are provided in Webpack. A good place to start is the ExternalModuleFactoryPlugin or DllReferencePlugin.

基本上,你为 NormalModuleFactory 创建了一个插件它接受模块的请求,你匹配那些应该解析你正在生成的模块的模块,你可以用模块异步响应。

Essentially, you create a plugin for the NormalModuleFactory which takes requests for modules, you match those which should resolve to the modules you are generating and you can asynchronously respond with a Module.

这篇关于Webpack动态创建一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:54