Moritur
Moritur

Reputation: 1748

Inlined Webpack JS file doesn't work

I have a webpack project (based on https://github.com/vuejs/vue-webpack-example) which generates an index.html file and a javascript file containing the application.

Everything works fine when I include the JavaScript like this:

<script src="static/js/app.js"></script>

When I try to include the contents of static/js/app.js directly in a script tag (because we need to end up with a single .html file) it doesn't work anymore. It looks like the javascript doesn't get exectuted at all:

<script>!function(e){function t(i){if(n[i])return...</script>

I extracted the application into 3 files (manifest.js, vendor.js and app.js) where vendor.js contains the libraries I need from node_modules. It works as long as I don't include vendor.js directly. So I can inline the manifest.js and app.js but not vendor.js.

Any ideas why the inlined js doesn't work but the included js via an url does work? Until now I thought js would behave exactly the same, no matter how it's included.

Upvotes: 3

Views: 748

Answers (2)

Moritur
Moritur

Reputation: 1748

I figured out what's wrong.

Some browsers (I tested Safari and Chrome on Mac) seem to not like <script> tags which have an opening script tag somewhere inside them. Even though all the closing script tags are escaped (like document.write("</script"+">"))

Strangely this does work in simple example like this one:

<script>
    document.write("<script>alert(1)</script"+">")
</script>

In complex examples (like this one: https://gist.github.com/Sopamo/f2a591b4afaa91238516b82006e85845) it only works when all <script> tags are "escaped". Maybe someone can find out what's the difference between the simple and the complex example.

In my case I used the inline example of the html-webpack-plugin which I modified as follows:

script(type="text/javascript") !{compilation.assets[jsFile.substr(htmlWebpackPlugin.files.publicPath.length)].source().replace(/<script>/g,'<script"+">')}

Note the replace() call at the end.

Upvotes: 2

ragnar
ragnar

Reputation: 1302

You shouldn't need to include the app.js file. If you run npm run build from project folder it will create all files needed to run the application inside the dist folder.

Remember also that the app must be served from an HTTP server in order to work.

Upvotes: 0

Related Questions