02-webpack packaging style files

In actual development, we must avoid requesting static resources twice to avoid waste. Therefore, you must learn to use webpack to package style files
Insert image description here
(1) First initialize package.json. Input instructions: npm init
Download and install webpack. Input instructions:npm install webpack webpack-cli -g npm install webpack webpack-cli -D

(2) Download and install the loader packagenpm i css-loader style-loader less-loader less -D

Output in terminal

  webpack src/js/main.js -o build/js/built.js --mode=development

webpack.config.js

const path=require('path')
module.exports={
    
    
    entry: path.join(__dirname,'./src/main.js'),
       //入口,表示使用webpack打包哪个文件
    output:{
    
     //输出文件相关的配置
        path:path.join(__dirname,'./dist'),//把文件打包到哪个目录去
        filename:'bundle.js' //指定输出的文件的名字
    },

    module:{
    
    //这个节点,用于配置所有的第三方模块加载器
        rules:[ //所有第三方模块的规则
            {
    
    test:/\.css$/,use:['style-loader','css-loader']},
            {
    
     test: /\.less$/,use: ['style-loader','css-loader',
                  // 将less文件编译成css文件
                  // 需要下载 less-loader和less
                  'less-loader'
                ]
              }
        ]
    },
    mode:'development'//开发模型
}

main.js

import './index.css';
import './index.less';

Insert image description here
Insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../dist/bundle.js"></script>
</head>
<body>
    <h1 id="t">我是谁</h1>
</body>
</html>

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41309350/article/details/122681553