17

I had a Vite project for Vue2, It include a static html file.

like following

import template from 'editor.html';
export default {
    template: template
}

When I ran yarn dev, Terminal output:

node_modules/@gaoding/editor-framework/lib/base/editor.js:23:21: error: No loader is configured for ".html" files: node_modules/@gaoding/editor-framework/lib/base/editor.html 23 │ import template from './editor.html';

I tried to add some plugin below in vite.config.ts, But all of these didn't work.

@rollup/plugin-html

rollup-plugin-html

rollup-plugin-htmlvue

How can I solve this problem.

noahlam
  • 171
  • 1
  • 4

2 Answers2

21

adding ?raw at the end of the import can address the issue:

import template from "./contact-list.html?raw";  

I'm still looking for a solution how to set it globally for all HTML files.

Marcin Wosinek
  • 793
  • 3
  • 8
  • 1
    Documentation reference : https://vitejs.dev/guide/assets.html#importing-asset-as-string Very usefull thanks – tchartron Sep 03 '22 at 13:42
  • while this indeed works, if you're using typescript, it will raise the error `Cannot find module '*?raw' or its corresponding type declarations.`. In order to fix it, just declare `"types": ["vite/client"]` under `compilerOptions` in your `tsconfig.json` file. Reference: https://stackoverflow.com/a/74793817/12068529 – Ricardo Passos Dec 22 '22 at 03:08
4

I know that this is super old, however I found something that worked for me.

// vite.config.js
const htmlImport = {
  name: "htmlImport",
  /**
   * Checks to ensure that a html file is being imported.
   * If it is then it alters the code being passed as being a string being exported by default.
   * @param {string} code The file as a string.
   * @param {string} id The absolute path. 
   * @returns {{code: string}}
   */
  transform(code, id) {
    if (/^.*\.html$/g.test(id)) {
      code = `export default \`${code}\``
    }
    return { code }
  }
}

export default {
  plugins: [ htmlImport ]
}

The above code allows me to import an html file as a string without the ?raw. I needed this to migrate AngularJS 1.5 from gulp to Vite and it is working rather well.

You can find a point of reference here

Jon Taylor
  • 51
  • 2