Home > Software engineering >  Is there a way to assign the content of a file to a specific variable using webpack?
Is there a way to assign the content of a file to a specific variable using webpack?

Time:05-31

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?

CodePudding user response:

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.

  • Related