Introduction of static resources

The development environment has been set up in the previous chapter. Now we begin to gradually enrich the content of the project. This chapter is the introduction of static resources.

Install dependencies

By default, WebPack only knows JavaScript and only knows what to do with it. If there are other types of files in your project and you want WebPack to package them, you need to install the loader.

What is loader? The following content comes from Webpack Chinese website

Loader is used to convert the module source code. Loader allows you to preprocess files when importing or “loading” modules. As such, Loader is similar to “tasks” in other build tools and provides a powerful way to handle the front-end build steps. Loader can convert files from different languages (such as TypeScript) to JavaScript, or convert inline images to data urls. Loader even allows you to import CSS files directly into JavaScript modules!

css-loader

$ yarn add css-loader style-loader -D
Copy the code

Create the first CSS file in the SRC folder and name it index.css

.hello{
   color:red;
}
Copy the code

Modify theindex.tsfile

Modify the webpack. Config. Js

 module: {
        rules: [
          +  {
          +    test: /\.css$/,
          +    use: ['style-loader'.'css-loader'[+}],}Copy the code

file-loader

File-loader is used to import image files

$ yarn add file-loader -D
Copy the code

Modify the index.ts file and add a PNG image to the SRC folder

import img from  "./index.png"
let image: HTMLImageElement = document.createElement("img");
image.src = img;
document.body.append(image);
Copy the code

Modify the webpack. Config. Js

 module: {
      rules: [
          +{
          +   test: /\.(png|jpe? g|gif)$/i,
          +  use:['file-loader'], +},],},Copy the code

The last

That’s all about the CSS and image configuration. Now run the launch command and you can see that the words on the page are already red and an image has been added

More loader

Get the code