webpack入门

webpack入门

模块的打包器
三大特点:
1.代码分割
2.代码loaders
3.插件系统

webpack的安装和使用

1.在项目文件下初始化npm,(npm init)
2.安装:

npm install webpack --save-dev

webpack是不支持css文件,则需要安装css-loader,style-loader(npm install css-loader style-loader --save-dev),但是还是要指定相应的loader说明(require('css-style!css-loader!./style.css'));
css-loader:是处理webpack支持.css文件。
css-style:是将.css文件新建style标签插入到header标签中
当然直接在命令行中整体指定loader:
webpack hello.js hello.bunder.js --modul 'css=style-loader!css-loader'
后面直接跟--weach,会实时跟新打包

webpack基本配置

在项目下新建src(资源文件目录),dist(打包后的静态资源的目录)
给项目新建webpack.config.js文件:

module.exports = {
    entry:'./',//打包的入口文件开始
    output: { //打包以后的文件放在什么地方
        padth: './dist/js',
        filename: 'bundle.js',//打包后的文件名

    }
}

运行config命令:webpack --config webpack.config.js(或者直接webpack)

也可以在package.json文件下的script对象内配置自己的webpack运行脚本;

"webpack":"webpack --config webpack.config.js --progress --displar-modules --colors --display-reason"

运行webpack: npm run webpack

entry

1.上述相同
2.两个平行的文件

entry: ["../","../"]; 

3.给entry传一个对象(使用场景多页面应用)

entry: {
    page1: "../",
    page2: ["../","../"]//多个路径的 
}

output

 output: { //打包以后的文件放在什么地方
        padth: './dist/js',
        filename: 'bundle.js',//打包后的文件名

    }
    //filename中不要设置绝对路径,因为path中设置了绝对路径

如果创建的entry是多个的,要采用一些占位符保证输出的是唯一的。有三个占位符[name][hash][chunkhas]

[name]: entry对象输入
[hash]: 每次打包时会产生一个个哈希值
[chunkhash]: 每一个chunkhash的哈希值 

自动生成项目中的html

webpack的插件:html-webpack-plugin

npm install html-webpack-plugin --save-dev

使用:webpack.config.js中应用

var htmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    plugins: [
        //new htmlWebpackPlugin();//之后会自动生成html文件自动添加js,并不是根目录,和根文件的html每日有对应,给插件传参数
        new htmlWenPlugin({
            template: "index.html",//根目录下的index.html
            filename: "index-[hash].html",//可以对生成的文件命名
            inject: "head",//指定标签放置的位置
            title: "webpack is good",
            //<%= htmlWebpackPlugin.options.title %> 就可以取到
            date: new Date(),//同样可以取到值
            //<% %>模板引擎的取值方式,也可以遍历,使用js代码
            /*<% for(var key in htmlWebpackPlugin.files) {%>
             <% key %>:<% = JSON.stringify( htmlWebPackPlugin.files[key] ) %>
            } %>*/
        });
    ]
}
原文地址:https://www.cnblogs.com/intelwisd/p/8564323.html