Liam Steele
Liam Steele

Reputation: 146

Inline a single javascript file with imports in webpack

I need to inline a little bit of javascript in my index.html. The js is essentially:

import smallFunction from './smallFunction';
const name = smallFunction();
document.querySelector('#id').setAttribute('href', `/path/${name}.${__webpack_hash__}.css`);

I'm using webpack 4 with HtmlWebpackPlugin and webpack.ExtendedAPIPlugin. When using HtmlWebpackInlineSourcePlugin, it either inlines my entire js bundle:

inlineSource: '.js$'

or doesn't inline anything with either of the following:

inlineSource: 'myFile.js$'

inlineSource: './path/myFile.js$'

I've also tried referencing the files from my javascript entry point to make sure webpack is aware of them, but that didn't make a difference.

Is it possible to inline just one javascript file (including imports) using webpack?

Upvotes: 1

Views: 1777

Answers (1)

Liam Steele
Liam Steele

Reputation: 146

It is possible by having myFile as an additional entry point.

This allows inlineSource to detect it, and allows you to use your current loader stack (e.g. babel transpiling).

Note that inlineSource is a regular expression in string form.

// Entry points
entry: {
  main: './src/main.js',
  // Separate entry point for inlined js
  injectCss: './src/js/injectBrandCss.js'
}

// HtmlWebpackPlugin options
inlineSource: 'myFile.*\.js$'

Note that you may not be able to call any functions that are inlined due to the minification.

Upvotes: 1

Related Questions