marverix
marverix

Reputation: 7705

Load CSS with <link> tag and HTMLWebpackPlugin

I want to use <link> (it's important - I don't want to use a <style>) tag to load external CSS (from npm dependencies). I'm using HTMLWebpackPlugin.

I have tried something like this:

<link href="style!css!file!~@internal-scope/package-name/dist/some.css" rel="stylesheet" id="important-id">

But Webpack keeps replacing the href with [Object object]. Which I assume is caused that Webpack is trying to use esModules? But when I'm turning off esModule with ...!file?esModule=false!... I'm getting errors like:

 Module not found: Error: Can't resolve './' in (...)

Also I tried to use only file-loader (as @felixmosh proposed) - still the same issue as above.

Upvotes: 1

Views: 3262

Answers (1)

felixmosh
felixmosh

Reputation: 35473

In your case chaining css-loader & style-loader are not relevant.

css-loader loads css and passes down an object with a selectors map + the css string. style-loader injects the css and returns the same object.

Therefore, you get [Object object].

Try to use only file-loader, which returns a string with the path to a static file, and emits the file to outputPath.

<link href="!!file?esModule=false!~@internal-scope/package-name/dist/some.css" rel="stylesheet" id="important-id">
// ---------^ these !! are important to prevent from running rest of the loaders which are suitable from your config.

BTW, why you are trying to inject it directly in the template and not import it in js and let HTMLWebpack do it's thing? (it is by default injects link tag to emitted css files)

Upvotes: 3

Related Questions