Warehouse addresses for the examples used in this article:gayhub

HtmlWebpackPlugin is used to generate an index. HTML file above, and the plug-in automatically adds packaged resources to the index. HTML file, so that we can open the index. HTML and see the js execution effect in the browser. In this section we’ll use Webpack Loaders to handle the other three types of files we’ll use in our work: images, styles, and fonts.

Starting with this section, the test items in each section will be placed as the project resource types become more complexdemo/Is no longer the document root directory.

Loaders

Loaders is very simple, with three simple points:

  • You can use Loaders to package any static resource other than Javascript
  • Writing a Loader in Node.js is easy
  • Loader can be activated in either of the following ways:
    • Add in the import statementloaderName!, such asimport 'style-loader! css-loader? modules! ./css/test.css'
    • rulesFor details, see the following

Processing images

file-loader

yarn add file-loader
Copy the code

Usually, we just need to copy the image to (package) the target directory, in which case we use File-laoder

{
  test: /\.(png|jpe? g|gif|webp)$/.use: [{loader: 'file-loader'.options: {
        // File name
        name: '[name].[ext]'.// Output path
        outputPath: 'imgs/'}}}]Copy the code

After executing the webpack command, we can see that the image has been packed into the dist/imgs/ directory with the name unchanged.

url-loader

yarn add url-loader
Copy the code

When our image file has some small tags, if each small tag is requested independently, it is obviously a waste of bandwidth, which is not the rule. At this point we need to have a Sprite image like solution, integrating multiple small images into one request. Url-loader can do this, but unlike Sprite, it converts base64 encoded images that are smaller than the specified size into packaged code.

{
  test: /\.(png|jpe? g|gif|webp)$/.use: [{loader: 'url-loader'.options: {
        // File name
        name: '[name].[ext]'.// Output path
        outputPath: 'imgs/'.// Images smaller than 10K are base64 encoded
        limit: 10240}}}]Copy the code

After executing the webpack command, we can see that only the doraemon.jpg image is packaged into the dist/imgs/ directory, and the other five small images are packaged into A string of Base64 code (in dist/dist. Js).

  • Graphs greater than 10K

    / * * * / "./ SRC /imgs/ doraemon. JPG":
    / *! * * * * * * * * * * * * * * * * * * * * * * * * * * *! * \! ***./ SRC /imgs/ doraemon. JPG ***! A \ * * * * * * * * * * * * * * * * * * * * * * * * * * * /
    / *! no static exports found */
    / * * * / (function(module, exports, __webpack_require__) {
    
    eval("Module. exports = __webpack_require__.p + \"imgs/ doraemon.jpg \"; \n\n//# sourceURL=webpack:///./src/imgs/%E5%A4%9A%E5%95%A6A%E6%A2%A6.jpg?");
    
    / * * * / }),
    Copy the code
  • Graph less than 10K

    / * * * / ". / SRC/imgs/share. PNG":
    / *! * * * * * * * * * * * * * * * * * * * * * * * * *! * \! / SRC /imgs/ share.png ***! A \ * * * * * * * * * * * * * * * * * * * * * * * * * /
    / *! no static exports found */
    / * * * / (function(module, exports) {
    
    eval("module.exports = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAR7ElEQVR4Xu2dC9CuUxXHf0TkfolQrinkLspRKEVuRVO55Ci3kqQkoiJ3iVDINYVJLplyHddBkqjEYEopFBWSJGLk0vzNPjnzfef73vfd79577f0+a82YY+Y8e621//v5n3fvZ6/LTLg4Ao7AhAjM5Ng4Ao7AxAg4QfztcAQmQcAJ4q+HI+AE8XfAEYhDwH9B4nDzUR1BwAnSkYX2acYh4ASJw81HdQQBJ0hHFtqnGYeAEyQONx/VEQScIB1ZaJ9mHAJOkDjcfFRHEHCCdGShfZpxCDhB4nDzUR1BwAnSkYX2acYh4ASJw81HdQQBJ0hHFtqnGYeAEyQONx/VEQScIB1Z6ITTXBGYAqwBrAusNAPdjwG3AjeHP/X/TyX0oZgqJ0gxqJs2tBqwI/ARYNHImVwJnAWcFzneZJgTxAT2ZoyuBRwCbJzQ44eAI4CTE+rMpsoJkg3aphXPCRwF7AbkekfuArYD9Ge1kmvy1U7YHeuJwHrA2cCSPZ8c/oHngcPCfy8Mry69BidIekxb1nhA2FKVnoMO85sBT5Q23MueE6QXQt35+1OAXQ2new/wHuCvhj6MM+0EqWk17Hw5EtjXzvz/Lf8W0IeBpyvw5WUXnCC1rISdHzsA37MzP86yPgdvUos/TpBaVsLGD1323QLMamN+QqsHAQfX4JMTpIZVsPPhfmApO/OTWl473MKbuucEMYXf1Lj+lT7Q1IPJjd8RwllesvTRCWKJvp3txYA/ArPbudCX5anAOX09mek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JRU5ErkJggg==\"\n\n//# sourceURL=webpack:///./src/imgs/%E5%88%86%E4%BA%AB.png?");
    / * * * / })
    Copy the code

Processing style

If we don’t use loader to handle styles, You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

CSS

yarn add css-loader style-loader
Copy the code
  • css-loaderParsing CSS files
  • style-loaderInsert the style into the DOM

Loader executes from right to left and from bottom to top

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

At this point, executing webpack will pack correctly, but instead of generating a.css file under dist/, the style is inserted as a style tag in the head tag of index. HTML (viewed in the browser console, the style file is in JS before insertion).

CSS preprocessor

Since I started using the preprocessor in my project after watching the “Gao-fang-ele. me” course taught by Huang Yi, I prefer stylus, which is also used in the examples in this article.

stylus-loaderExists in the default projectstylusDependency, so installstylus-loaderDon’t forget to installstylus

yarn add stylus stylus-loader css-loader style-loader
Copy the code
{
    test: /\.styl(us)? $/.use: [
        'style-loader',
        {
            loader: 'css-loader'.options: {
                importLoaders: 1 // Number of loaders executed before CSS-loader}}, {loader: 'stylus-loader'.options: {
                preferPathResolver: 'webpack' // Prefer webpack for path resolution. Use the stylus-Loader for path resolution if not found}}}]Copy the code

PostCSS

A few years ago there was a real pain in writing CSS, you had to prefix certain properties differently for different browsers, like -moz-transform for Firefox and -ms-transform for IE, but with PostCSS you just had to write unprefixed properties, PostCSS prefixes your CSS properties based on data from Can I Use.

yarn add postcss-loader -D
Copy the code
{
    test: /\.styl(us)? $/.use: [
        'style-loader',
        {
            loader: 'css-loader'.options: {
                importLoaders: 2 // Number of loaders executed before CSS-loader}},'postcss-loader',
        {
            loader: 'stylus-loader'.options: {
                preferPathResolver: 'webpack' // Prefer webpack for path resolution. Use the stylus-Loader for path resolution if not found}}}]Copy the code

PostCSS Configuration file postcss.config.js for automatic completion (autoprefixer plug-in required)

yarn add autoprefixer -D
Copy the code

postcss.config.js

module.exports = {
  plugins: [
    require('autoprefixer')]}Copy the code

In this case, run the webpack command. Transform rotate(180deg) is translated into -webkit-transform: rotate(180deg). transform: rotate(180deg); .

Two points to note:

  • postcss-loaderIn the order ofcss-loaderPrevious Execution
  • This can be configured in Webpack configuration JSpostcss-loaderPostCSS is configured using options, but it is recommended to add it in the project root directorypostcss.config.jsConfiguration files that make it easier for others to know that you are using PostCSS.

Separate style files from JS

As mentioned above, style-loader inserts styles into HTML files, which reduces the number of requests. However, normal project style files can take up quite a bit of volume. Remember that our style files are stored in JS files before we insert index.html, so JS files can be quite large, and we may need a clearer structure of the product. So you should also know how to separate styles from JS – using the MiniCssExtractPlugin.

yarn add mini-css-extract-plugin -D
Copy the code

Replace style-loader with MiniCssExtractPlugin loader

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  module: {
    rules: [{test: /\.styl(us)? $/.use: [{loader: MiniCssExtractPlugin.loader,
                    options: {
                        publicPath: '.. / '.hmr: process.env.NODE_ENV === 'development'.reloadAll: true}, {},loader: 'css-loader'.options: {
                        importLoaders: 2 // Number of loaders executed before CSS-loader}},'postcss-loader',
                {
                    loader: 'stylus-loader'.options: {
                        preferPathResolver: 'webpack' // Prefer webpack for path resolution. Use the stylus-Loader for path resolution if not found}}]}],},plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].css'.chunkFilename: 'css/[name].css',})]};Copy the code

After executing the webpack command, you can see that main. CSS is generated in the dist/ CSS directory and introduced in index.html.

Working with font files

Font files are similar to images, just copy and place in the dist/fonts/ directory, still using file-loader/url-loader.

{
    test: /\.(woff2? |eot|ttf|otf|svg)(\? . *)? $/i.use: {
        loader: 'url-loader'.options: {
            limit: 4096.name: '[name]_[hash:5].[ext]'.outputPath: 'fonts/'}}}Copy the code

By the way, SVG is now more popular for drawing ICONS, and drawing paths existiconfong.jsIn (Ali icon library download example), at this time remember not toiconfong.jsOn thesrc/Directory, because of packagingiconfont.jsIt doesn’t make any sense. It just takes longer to pack. It should be placed in a static directory without packaging, such as vue-CLI 2static/And the vue – cli 3public/And reference them in HTML to use when packagingCopyWebpackPluginstatic / publicCopy the entire folder todist/.

Reference documentation

  • [ Webpack Docs ] Loaders