zoukankan      html  css  js  c++  java
  • Webpack

    webpack是一个前端资源加载打包工具,它将根据模块的依赖关系进行静态分析,然后

    将这些模块按照指定的规则生成对应的静态资源,webpack可以将多种静态资源js,css,less转换成一个静态文件,减少了页面的请求。

    1.全局安装

    npm install -g  webpack webpack-cli

    2.安装后查看版本号

    webpack -v

    3.在根目录下创建文件 webpack.config.js   ,注意,这个是固定的

    const path = require("path"); //Node.js内置模块
    module.exports = {
        entry: './src/main.js', //配置入口文件
        output: {
            path: path.resolve(__dirname, './dist'), //输出路径,__dirname:当前文件所在路径
            filename: 'bundle.js' //输出文件
        },
        module: {
            rules: [  
                {  
                    test: /.css$/,    //打包规则应用到以css结尾的文件上
                    use: ['style-loader', 'css-loader']
                }  
            ]  
        }
    }

    4.创建 js或者css文件

    #####common.js
    exports.info = function (str) {
        document.write(str); //浏览器输出
    }
    
    
    #####  utils.js
    exports.add = function (a, b) {
        return a + b;
    }
    
    
    ######  main.js
    const common = require('./common.js')
    const utils = require('./utils.js')
    
    //css文件引入
    require('./style.css')
    
    common.info('hello common '+utils.add(1,2))
    
    #######style.css
    body {
        background-color: red;
    }

    5.执行 命令打包 webpack

    PS E:qianduan20200326webpackdemo> webpack
    Hash: 03a20b3f36fcb7642877
    Version: webpack 4.42.1
    Time: 625ms
    Built at: 2020-03-29 12:19:33
        Asset      Size  Chunks             Chunk Names
    bundle.js  4.76 KiB       0  [emitted]  main       
    Entrypoint main = bundle.js
    [0] ./src/main.js 168 bytes {0} [built]
    [1] ./src/common.js 78 bytes {0} [built]
    [2] ./src/utils.js 53 bytes {0} [built]
    [3] ./src/style.css 561 bytes {0} [built]
    [5] ./node_modules/css-loader/dist/cjs.js!./src/style.css 273 bytes {0} [built]
        + 2 hidden modules
    
    WARNING in configuration
    The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 
    'mode' option to 'development' or 'production' to enable defaults for each environment.       
    You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
    PS E:qianduan20200326webpackdemo>

    目录结构见下图:

  • 相关阅读:
    jQuery中$.proxy()的原理和使用
    JS中各种宽度、高度、位置、距离总结
    js中得call()方法和apply()方法的用法
    google浏览器翻译失败解决方案
    js区分移动设备与PC
    知识积累
    Django
    leetcode 27.Remove Element
    leetcode 28. Implement strStr()
    21. Merge Two Sorted Lists
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/12591631.html
Copyright © 2011-2022 走看看