Cannot inject script if I add the type attr
I encountered with the vite-plugin-html plugin. I have been attempting to dynamically inject a script file into my HTML using this plugin, but I have found that when I include the type attribute in the script tag, the injection seems to be skipped.
Here are the steps to reproduce the issue:
-
Install the vite-plugin-html plugin in your project
-
Add a script file to your project with a type attribute, for example:
<script type="module" src="./my-script.js"></script> -
Configure the vite-plugin-html plugin in your vite.config.js file to include this script file using the inject option:
import { defineConfig } from 'vite'
import html from 'vite-plugin-html'
export default defineConfig({
plugins: [
html({
inject: {
injectData: {
title: 'My App',
myScript: '<script type="module" src="./my-script.js"></script>'
}
}
})
]
})
In your HTML file, include the <%- injectScript %> variable:
<!DOCTYPE html>
<html>
<body>
<%- injectScript %>
</body>
</html>
Run the project with the vite build command and observe that the script file is not injected into the HTML. I have found that when I remove the type attribute from the script tag in my script file, the injection works as expected. However, I need to include the type attribute in order to use ES modules.
Please let me know if there is a workaround for this issue, or if a fix can be included in a future release of the plugin.
Thank you for your attention to this matter.
In fact, the content of my-script.js has been built into the js asset. It was built by Vite. If this is not what you expect, use CDN import.
<script type="module" src="https://unpkg.com/[email protected]/source/index.js"></script>
by the way. It seems that vite-plugin-html is no longer being updated, and you can try vite-plugin-htmlx