Since webpack was replaced with Vite after VUe3, the original require syntax is no longer valid. For dynamic Mosaic pictures, there are currently two effective methods I have used.

The first kind of new Url

The website says: “In fact, Vite doesn’t need to deal with this code during development! At production build time, Vite does the necessary transformations to ensure that the URL still points to the correct address after being packaged and hashed.”

Therefore, the following method development phases do not need to be understood.

First bind a function to SRC and pass the required image name to the function.

<img :src="getImage(name)">
const getImage = (name: string) :string= > {
    return new URL(`assets/image/${name}.png`.import.meta.url).href
}
Copy the code

New URL and import.meta. URL.

new Url

Create a new URL object

// url Full URL, or path only (if base is set) // [base] -base -- Optional Base URL: If this parameter is set, and the parameter URL has only path, the URL will be generated from this base. new Url(url, [base])Copy the code

import.meta

The import.meta object contains information about the current module.

Its content depends on its context. In the browser environment, it contains the URL of the current script, or if it is in HTML, the URL of the current page.

So you can print import.meta:

There’s a URL property in there

In summary, the return value of the entire function. Print it out

The href value inside is the address of the current image

The second import. Meta. Glob

In Vite, Glob imports are provided to import multiple modules from the file system.

const modules = import.meta.glob("./dir/*.js")
Copy the code

Vite compiled:

const moudles = {
    './dir/foo.js': () => ('./dir/foo.js'),
    './dir/bar.js': () => ('./dir/bar/js')
}
Copy the code

The matched files are lazily loaded by default through dynamic imports and split into separate chunks at build time.

Please note:

  1. This is a Vite only feature, not a Web or ES standard

  2. The Glob pattern is treated as an import identifier: it must be a relative path (starting with a./ and resolving relative to the project root), and globs from dependencies are not supported.

Glob imports can only be used with default imports (not by name or import * as… .

const getImage = (name: string): Const picModules = import.meta. GlobEager ('./image/*'); const picModules = import.meta. / / get the specified image const path = (`. / images / ${name}. PNG `); return picModules[path].default } <img :src="getImage(name)">Copy the code

It’s important not to forget to add.defalut

The above is vue3 VitE2 dynamic image pouring, I use two syntax