Webpack Best Practice Series (10)

Source: Internet
Author: User

10.css modularity 10.1. What is a CSS module?

CSS module is all class name only local scope of the CSS file, when you import a CSS file in a JavaScript module, the CSS module will define an object, the names of the classes in the file dynamically mapped to the JavaScript scope can be used in the string, The CSS module is not the official standard in the browser (official spec) or practice (Implementation) but a (with the help of Webpack or browserify) change the scope of the class name and selector to the current file (similar to a namespace) The build process

In layman's terms, CSS modularity is the CSS file as a module to use, the introduction of a CSS file, the time to get an object, through the object. This form of class name to use CSS style, the advantage is that all class names hang on an object, prevent the same name of the class conflict

10.2. Using CSS modularity in Webpack

First, write a test code in the Src/assets/css/index.css file

. pbox{    border:4px solid black;    color:red;}

  

Write a test code in Src/assets/js/index.js
Introduction of Icon Font//import "FONT-AWESOME/CSS/FONT-AWESOME.CSS"//import picture imported imgsrc from '. /img/nodeing.jpg '//Insert the picture into the HTML page//document.getElementById ("box"). InnerHTML = '  '// Test CSS Module import styles from '. /css/index.css ' document.getElementById ("box"). InnerHTML = ' <p class= ' ${styles.pbox} ' >hello nodeing</p> `

  

At this point, run NPM start is not see CSS style, we must add the configuration in Webpack.config.js, turn on CSS modularization, configuration changes are as follows:

{    test:/\.css$/, use    : [        ' Style-loader ',        {            loader: ' Css-loader ',            options: {                name: ' Assets/css/[name]_[hash:4]. [ext] ',                module:true,                localidentname: ' [Path]-[name]-[local]-[hash:base64:6] '}}       ]},

  

Once the configuration has been modified, NPM start runs to see that the CSS is in effect,

Module:true, which means to turn on the modular

Localidentname: ' [Path]-[name]-[local]-[hash:base64:6] ' indicates a custom class name, [path] represents the current CSS file path, [name] represents the current CSS file name, [local] represents the class name (e.g. Pbox), [Hash:base64:6] represents the hash string for Base64, and is 6 bits long

Next, we go to src/assets/js/index.js, the icon font CSS file comments removed

Import "Font-awesome/css/font-awesome.css" modified before import "Font-awesome/css/font-awesome.css"

  

Modified the JS file, the server will restart the refresh, but we found that although we introduced font-awesome.css this file, but the index.html in the icon is still not displayed, the following is the reference icon of the HTML code

<i class= "fa Fa-bath" aria-hidden= "true" ></i><i class= "fa fa-envelope-open" aria-hidden= "true" > </i><i class= "fa fa-microchip" aria-hidden= "true" ></i><i class= "FA Fa-user-circle-o" Aria-hidden= "true" ></i>

  

The reason these icons are not in effect is that we turned on modularity in Webpack, and when we turned on modularity, we used styles to form "object. Class name", while in index.html we were still using the original form, so it would not be effective

We now need to become: some of the CSS files need to open the modular, some of the CSS is not required to open the modular (for example: Font-awesome.css file in our case), this time, we have to modify the Webpack configuration, Customization of modular Files

{    test:/\.css$/, use    : [        ' Style-loader ',        {            loader: ' Css-loader ',            options: {                name: ' Assets/css/[name]_[hash:4]. [ext] ',                module:true,                localidentname: ' [Path]-[name]-[local]-[hash:base64:6] '            }        }       ],    This rule is required to turn on the modularity, set the included folder include    : [        path.resolve (__dirname, ' src/assets ')    },

  

We have configured a rule in the above rule, including the meaning of the inclusion, it is followed by an array, the array can write some path, the path of the CSS file is required to open the modular CSS file, since it is an array, then you can give multiple paths

Modified the configuration file, we must restart the server before the line, so CTRL + C first shut down the server, and then through NPM start to boot, this time we found an error, this times wrong is normal, because, when we in the ' Test:/.css$/' This regular expression rule adds a path to include, which means that only the CSS file under the Include path is processed, and the CSS file other than include does not have loader to handle it, so the error is reported:

ERROR in./node_modules/font-awesome/css/font-awesome.cssmodule parse failed:unexpected character ' @ ' (7:0)//Every time I see this sentence, You should have guessed that you would use the corresponding loader to process the corresponding file. Need an appropriate loader to handle the files type.| /* FONT path|  * -------------------------- */| @font-face {|   font-family: ' Fontawesome '; |   src:url ('. /fonts/fontawesome-webfont.eot?v=4.7.0 '); @./src/assets/js/index.js 3:0-44 @ multi (webpack)-dev-server/client?http://localhost:8080./src/assets/js/index.js

  

Since we understand the cause of the error, the solution is very simple, we go to modify the Webpack configuration file

{    test:/\.css$/, use    : [        ' Style-loader ',        {            loader: ' Css-loader ',            options: {                name: ' Assets/css/[name]_[hash:4]. [ext] ',                module:true,                localidentname: ' [Path]-[name]-[local]-[hash:base64:6] '            }        }       ],    This rule is required to turn on the modularity, set the included folder include    : [        path.resolve (__dirname, ' src/assets ')    ]},{    test:/\.css$/ , use    : [        ' Style-loader ',        {            loader: ' Css-loader ',            options: {                name: ' Assets/css/[name] _[hash:4]. [ext] ',            }        }       ],    //This rule does not need to be turned on for modularity, set the included folder include    : [        path.resolve (__dirname, ' Node_ Modules ')    ]},

  

From the above configuration, we can see that the solution is very simple, that is, we have the original processing of the CSS file configuration copy a copy, and then the copy of the copy of the changes, the CSS modular settings removed, and then set a path through the include: Path.resolve (__ DirName, ' node_modules '), this path is the installation path of the third-party package, Our Font-awesome.css file is in this path, which means that all files under this path will not be modularized, thus creating a structure that allows the file to be added to the path without the use of a modular function, in the same way that the file under which the path is to use the modular function, in another A CSS configuration item to add the path, to this, CSS modular basic content has been learned

Webpack Best Practice Series (10)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.