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.

styleInject breaks tree-shaking

See original GitHub issue

This function doesn’t have a /*#__PURE__*/ prefix, which breaks tree-shaking. Moreover, when I try to prepend it myself through inject option it gets stripped along with the entire string from the final bundle, which leaves you without CSS.

function inject(cssVariableName) {
  return (
    '\n' +
    `/*#__PURE__*/ (${styleInjectFork})(${cssVariableName}${
      Object.keys(styleInjectOptions).length > 0
        ? `,${JSON.stringify(styleInjectOptions, function(_key, value) {
            if (typeof value === 'function') {
              return value.toString();
            }
            return value;
          })}`
        : ''
    });`
  );
}

In my case, I forked styleInject, because it’s missing some features, so I had to compose it slightly different into the string (wrap it with brackets to turn it into expression, which is then invokable).

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
adi518commented, Oct 28, 2020

Hi, no. I was busy with other stuff. I intend to come back to this though, because I really need to solve this issue.

0reactions
ch99qcommented, Mar 17, 2022

Currently, the output from this plugin looks like this:

var css_248z = ".___2X_Ir{background-color:#4e707a;font-size:24px;color:#fff;cursor:pointer}";
var Button_module = {"button":"___2X_Ir"};
styleInject(css_248z);

If we want the styleInject(..) function to only execute when the export is imported, we need to make the following modifications:

  1. Wrap the styleInject(..) function call in an IIFE
  2. Use the /*#__PURE__*/ annotation
  3. Instead of exporting var Button_module = {"button":"___2X_Ir"};, we need to return Button_module from the IIFE
  4. Set the result of the IIFE to a variable. We can call this variable Button_module and change the name of the style mapping variable to styleMapping.

The code would look like this:

var css_248z = ".___2X_Ir{background-color:#4e707a;font-size:24px;color:#fff;cursor:pointer}";
var styleMapping = {"button":"___2X_Ir"};
var Button_module = /*#__PURE__*/(function() {
  styleInject(css_248z);
  return styleMapping;
})();

These changes can be made inside of the src/postcss-loader.js file, and it can be put behind a flag (e.g. noSideEffects). In order to produce the IIFE code above, this is the code I used inside of src/postcss-loader.js:

if (shouldExtract) {
    output += `export default ${JSON.stringify(modulesExported[_this.id])};`;
    extracted = {
      id: _this.id,
      code: result.css,
      map: outputMap
    };
} else {
    const module = supportModules ? JSON.stringify(modulesExported[_this.id]) : cssVariableName;
        output += `var ${cssVariableName} = ${JSON.stringify(result.css)};\n` + `var styleMapping = ${module};\n` + `export var stylesheet=${JSON.stringify(result.css)};`;
}

if (!shouldExtract && shouldInject) {
    output += typeof options.inject === 'function' ? options.inject(cssVariableName, _this.id) : '\n' + `import styleInject from '${styleInjectPath}';\n` + `export default /*#__PURE__*/(function() {\n  styleInject(${cssVariableName}${Object.keys(options.inject).length > 0 ? `,${JSON.stringify(options.inject)}` : ''});\n  return styleMapping;\n})();`;
}

For others looking at this comment, I also added a feature request to a similar plugin: Anidetrix/rollup-plugin-styles#168

Thank you so much for that! I created a pull request, let’s hope they merge it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Tree Shaking - webpack
Tree Shaking. Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of...
Read more >
rollup-plugin-postcss - Bountysource
Extracting CSS into a single file breaks treeshaking. I only want to ship critical styles. So as rollup turns every entry point to...
Read more >
Why you should build a React Component Library, and style it ...
Extracting CSS into a single file breaks treeshaking. We only want to ship critical styles. This wouldn't be ideal. We could do better....
Read more >
vis-timeline - UNPKG
node_modules/style-inject/dist/style-inject.es.js","../. ... (match[2] || ' ') + isoTimes[i][0];\n break;\n }\n }\n if (timeFormat == null) {\n config.
Read more >
Dependencies | umi_cps | npm - Open Source Insights
arrow_right antd. 3.26.16 Notes Relation Licenses Depende... Version 3.26.16 Published April 26, 2020 Description arrow_right father. 2.30.23 Notes Relation Licenses Depende... Version 2.30.23 Published September 15,...
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