1

Is there a way to assign the file contents directly to a variable/method without webpack generating an additional variable?

Currently webpack does something like this:

index.js

import scss from './styles.scss';
console.log(scss);

output.js (actual)

const styles = '...';
console.log(styles);

I want webpack to return the content of the styles.scss file directly to the console.log() method in the output without adding styles variable.

output.js (expected)

console.log('...');

I'm currently using my custom loader for reading .scss files:

css-loader.js

const sass = require('sass');

module.exports = function(source) {
    const result = sass.compile(this.resourcePath);

    return 'export default `\n' + result.css + '\n`';
};

I know there is a way to do this using the require() function but it generates a lot of extra code coming from webpack. Is there any other better way to do it?

exec1990
  • 15
  • 4
  • Note sure what you're trying to do exactly but have you considered using `fs/promises.readFilePath`? https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#fspromisesreadfilepath-options – Webber May 30 '22 at 18:15
  • The file is imported correctly, I have access to its contents, so everything is ok with it. The problem is that webpack in the `output.js` file first assigns me the contents of the imported file to a variable that it generates itself. And I want it to be immediately assigned to the variable I specified, which is in a different scope (and not at the top of the code, where `import` is used). @Webber – exec1990 May 30 '22 at 18:33
  • So it's really a scoping issue then. So there's no real requirement to not wanting webpacks default behaviour. Webpack has a few ways how to do that. https://stackoverflow.com/questions/37656592/define-global-variable-with-webpack – Webber May 30 '22 at 18:37
  • Honestly, I didn't think of using the `webpack.DefinePlugin` method in that way (to assign the contents of the file as a global variable and then use it) but it works perfectly. Thank you! btw Sorry but I'm new to Stackoverflow and from what I've read you probably need to write this comment as an answer so I can accept it. @Webber – exec1990 May 30 '22 at 19:54
  • Glad it helped you. Added an answer @exec1990 – Webber May 30 '22 at 20:31

1 Answers1

1

So it's really a scoping issue. So there's no real requirement to not wanting webpacks default behaviour.

Webpack has a few ways how to do that. See this other answer for how to define a global variable, which is Webpacks way of doing what you want to do.

Webber
  • 4,672
  • 4
  • 29
  • 38