Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello, I’m Shanyue.

This is my front end engineering knowledge card collection 6/36 published in Denver

In the front end, web pages can only load javascript resources, and even in Node, only javascript and JSON resources can be loaded. How do tools like WebPack, Rollup, and Vite load images and JSON resources?

In packaging tools like Webpack, everything is claimed to be a module.

When webPack needs to load non-javascript resources such as JSON in such a wrapper, it converts them into modules through the module loader.

Take JSON as an example:

// user.json contents
{
  "id": 10086."name": "shanyue"."github": "https://github.com/shfshanyue"
}
Copy the code

In a modern front-end, we use import to import resources when we treat it as a Module.

import user from './user.json'
Copy the code

Our packers, such as Webpack and rollup, load JSON resources in the following way.

This way it will be treated as a normal Javascript resource.

// The actual user.json is compiled into the following
export default {
  "id": 10086."name": "shanyue"."github": "https://github.com/shfshanyue"
}
Copy the code

The following is an example of a JSON-loader that handles such non-JS resources in webpack:

Mini-code :json-loader visible minimum implementation and examples.

module.exports = function (source) {
  const json = typeof source === 'string' ? source : JSON.stringify(source)
  return `module.exports = ${json}`
}
Copy the code

What about the pictures?

import mainImage from 'main.png'

<img src={mainImage} />
Copy the code

Even simpler, it will be replaced by its own path. The sample is as follows

export default `$PUBLIC_URL/assets/image/main.png` 
Copy the code

So how do you load a CSS script? There are various DOM apis involved here and how to split it into a.css file, which is a lot more complicated, but I’ll cover that in the next article.