Webpack

不打扰是莪最后的温柔 提交于 2020-03-29 13:30:20

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:\qianduan\20200326\webpackdemo> 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:\qianduan\20200326\webpackdemo>

 

目录结构见下图:

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!