Generate single module with webpack, with optional-to-load parts of the same module

可紊 提交于 2021-01-29 06:45:32

问题


I've created a library of date/time functions. (Why? I need some special features other libraries like Moment.js don't have.) There are some big chunks of data for handling historical Daylight Saving Time info that most users won't need, so I'd like them to be something that can be loaded optionally.

This works fine when code is being loaded directly from npm libraries, but I'm trying to make the same code work when loaded as scripts directly into a web browser from unpkg.com. I'm finding that when I load the main code and one of the optional parts like this:

  <script src="https://unpkg.com/@tubular/time/dist/index.umd.js"></script>
  <script src="https://unpkg.com/@tubular/time/dist/timezone-large-alt.umd.js"></script>

...the loading of the second script kills off the code from the first script, instead of merging with it as an addition to the same module, like I'd want it to.

Here's the relevant part of my webpack config:

module.exports = env => {
  const target = env?.target === 'umd' ? 'es5' : 'es2015';
  const libraryTarget = env?.target === 'umd' ? 'umd' : 'commonjs';
  const library = env?.target === 'umd' ? 'tbTime' : undefined;

  const config = {
    mode: env?.dev ? 'development' : 'production',
    target,
    entry: {
      index: './dist/index.js',
      'timezone-large': { import: './dist/timezone-large.js', dependOn: 'index' },
      'timezone-large-alt': { import: './dist/timezone-large-alt.js', dependOn: 'index' }
    },
    output: {
      path: resolve(__dirname, 'dist'),
      filename: `[name].${env?.target || 'cjs'}.js`,
      libraryTarget,
      library
    },

It's the "umd" target that I'm using for browser scripts.

If I switch the order of the <script> tags, my main library code survives, but the large timezone data is gone.

Is there anyway to tell webpack to generate a module that somehow recognizes that a same-named module has already been loaded, and then merges itself with the existing module rather than replacing it?

来源:https://stackoverflow.com/questions/65444973/generate-single-module-with-webpack-with-optional-to-load-parts-of-the-same-mod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!