question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dynamic imports of static files are not working as expected

See original GitHub issue

Current Behavior

I have a folder full of country flags SVGs, and I need to display a specific one. I think that the best solution here is to just dynamically import it into an img.

<Select renderValue={value => <img src={require(`../flags/${value}.svg`)} />}>

I ended up spending whole day trying to figure out how to make it work. Also tried ES6 imports and just setting src to ../flags/${value}.svg (without using any imports), but the storybook keeps failing with an error Module not found: Error: Can't resolve '../flags' in... all the time.

I’ve also tried to copy the whole flags folder into dist using rollup-plugin-copy with this config:

const copy = require('rollup-plugin-copy');
const rpts2 = require('rollup-plugin-typescript2');

module.exports = {
  rollup (config, options) {
    config.plugins = [
      ...config.plugins,
      copy({
        target: [{ src: 'src/flags/**/*', dest: 'dist/flags' }],
      }),
    ];

    config.plugins = config.plugins.map(plugin => {
      if (plugin && plugin.name === 'rpt2') {
        return rpts2({
          // properties that I added for demonstration purposes
          clean: true,
          objectHashIgnoreUnknownHack: true,
          // properties in the current internal implementation of tsdx
          typescript: require('typescript'),
          cacheRoot: `./.rts2_cache_${options.format}`,
          tsconfig: options.tsconfig,
          tsconfigDefaults: {
            compilerOptions: {
              sourceMap: true,
              declaration: true,
              jsx: 'react',
            },
          },
          tsconfigOverride: {
            compilerOptions: {
              target: 'esnext',
            },
          },
        });
      }

      return plugin;
    });

    return config;
  },
};

But the folder just won’t appear in the dist.

I’m not experienced with Rollup unfortunately, so maybe there’s someone who can help me use static files like these in my package?

Expected behavior

Correct handling of dynamic imports of static files.

Suggested solution(s)

N/A

Additional context

Your environment

Software Version(s)
TSDX 0.12.3
TypeScript 3.8.3
Browser Microsoft Edge 80 (Chromium)
npm/Yarn npm v6.13.7
Node 12.13.0
Operating System macOS 10.15.4 Beta (19E242d)

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:14 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
hnippscommented, Jun 30, 2020

Dynamic imports are not statically analyzable (as in, the bundler doesn’t know to include dynamically imported files). As far as I know no modern bundler can support them.

You have to either include all of the flags, or just the flags you know will be used.

@lpolito Just want to point out that Webpack supports partially dynamic imports, e.g. import(`./some/dir/${fileName}.js`)

https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

2reactions
agilgur5commented, Mar 4, 2020

@lpolito thanks for chiming in. I’ve dealt with this before but didn’t really remember the caveats. Your statement could use some modification though:

Dynamic imports are statically analyzable, that’s how code-splitting works in both Rollup and Webpack after all. The key difference, as @randex noticed, is the inclusion of string interpolation, which makes it much harder to statically analyze. There is an older Rollup issue on this in fact: https://github.com/rollup/rollup/issues/2463

@randex that’s an interesting example, I am curious how that simple config works. The Rollup issue points to virtual modules/custom resolvers as a potential solution but I’m not sure if there’s a simple way to do it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to use webpack dynamic import because of static ...
As long as I do not use any dynamic imports everything works as expected but when trying to dynamically load any chunks this...
Read more >
What they don't tell you about webpack dynamic imports
It appends content hashes independently from webpack and it does its best job to find internal links inside the static files to update...
Read more >
Dynamic imports solve all the problems, right? - Minko Gechev
There are two great things about this construct: Statically we can determine what symbols we import; Statically we can determine from which ...
Read more >
Advanced Features: Dynamic Import - Next.js
Dynamically import JavaScript modules and React Components and split your code into manageable chunks.
Read more >
Using with webpack - Jest
babelrc and Jest is not working as expected, try clearing the cache by running jest --clearCache . tip. If you use dynamic imports...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found