美文网首页
webpack深入与实战

webpack深入与实战

作者: happystory | 来源:发表于2017-04-04 22:55 被阅读0次

命令行

  1. 打包js
$ webpack hello.js bundle.js
// hello.js
require('./world.js');
function hello(str) {
  console.log(str);
}
  1. 打包css
    首先安装依赖:
cnpm i --save-dev style-loader css-loader

css-loader 使webpack能处理.css文件。
style-loader 把css-loader处理完返回的内容新建一个style标签并插入到head标签中。

// hello.js
require('./world.js');
require('style-loader!css-loader!./style.css');
function hello(str) {
  console.log(str);
}
hello('hello world');

提示:
也可以直接require('./style.css'),命令行执行:webpack hello.js bundle.js --module-bind 'css=style-loader!css-loader'

  1. 参数
  • --watch 监视文件变动并自动打包
  • --progress 显示打包进度
  • --display-modules 显示打包模块
  • --display-reasons 显示打包原因

基本配置

单入口

// webpack.config.js
var path = require('path');
module.exports = {
    entry: './src/scripts/main.js',
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: 'bundle.js'
    }
}

打包:$ webpack
如果命名为webpack.config.dev.js,则可以使用webpack --config webpack.config.dev.js

多入口

// webpack.config.js
var path = require('path');
module.exports = {
    entry: ['./src/scripts/main.js', './src/scripts/a.js'],
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: 'bundle.js'
    }
}

多页面

// webpack.config.js
var path = require('path');
module.exports = {
    entry: {
        main: './src/scripts/main.js',
        a: './src/scripts/a.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: '[name].[chunkHash].js'  // 还可以是hash(打包的hash值)
    }
}

生成html页面

安装插件:cnpm i --save-dev html-webpack-plugin
文档:https://www.npmjs.com/package/html-webpack-plugin

不指定模板

// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/scripts/main.js',
        a: './src/scripts/a.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: '[name].[chunkHash].js'
    },
    plugins: [
        new HtmlWebpackPlugin()  // 不指定模板
    ]
}

指定模板

// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/scripts/main.js',
        a: './src/scripts/a.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].[chunkHash].js',
        publicPath: 'http://www.cdn.com/'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: false,
            title: 'webpack is good',
            minify: {
                collapseWhitespace: true,
                removeComments: true
            }
        })
    ]
}

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title><%= htmlWebpackPlugin.options.title %></title>
        <script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
    </head>
    <body>
        <% for (var key in htmlWebpackPlugin.files) {%>
            <%= key %>: <%=  JSON.stringify(htmlWebpackPlugin.files[key]) %>
        <% } %>

        <% for (var key in htmlWebpackPlugin.options) {%>
            <%= key %>: <%=  JSON.stringify(htmlWebpackPlugin.options[key]) %>
        <% } %>

        <script src="<%= htmlWebpackPlugin.files.chunks.a.entry %>"></script>
    </body>
</html>
```

## 多页面应用

```
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/scripts/main.js',
        a: './src/scripts/a.js',
        b: './src/scripts/b.js',
        c: './src/scripts/c.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].[chunkHash].js',
        publicPath: 'http://www.cdn.com/'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'a.html',
            template: 'index.html',
            inject: 'body',
            title: 'a.html',
            chunks: ['main', 'a']
        }),
        new HtmlWebpackPlugin({
            filename: 'b.html',
            template: 'index.html',
            inject: 'body',
            title: 'b.html',
            chunks: ['b']
        }),
        new HtmlWebpackPlugin({
            filename: 'c.html',
            template: 'index.html',
            inject: 'body',
            title: 'c.html',
            excludeChunks: ['b']
        }),
    ]
}
```

## ES6

```
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                include: /src/,
                query: {
                    presets: ['env']
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: 'body'  
        })
    ]
}
或者
{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "babel": {
    "presets": ["env"]
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --progress --display-modules --colors --display-reasons"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-env": "^1.3.2",
    "html-webpack-plugin": "^2.28.0",
    "webpack": "^2.3.3"
  }
}
```

## 处理css

```
// webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                include: /src/,
                options: {
                    presets: ['env']
                }
            }, 
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader?importLoaders=1',
                        options: {
                            plugins: function() {
                                return [
                                    require('precss'),
                                    require('autoprefixer')
                                ]
                            }
                        }
                    }
                ]
            },
            {
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: function() {
                                return [
                                    require('precss'),
                                    require('autoprefixer')
                                ]
                            }
                        }
                    },
                    'less-loader'
                ]
            },
            {
                test: /\.scss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: function() {
                                return [
                                    require('precss'),
                                    require('autoprefixer')
                                ]
                            }
                        }
                    },
                    'sass-loader'
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: 'body'
        })
    ]
}
```

## 模板文件

```
{
                test: /\.html$/,
                loader: 'html-loader'
            },
```

## 图片

```
{
                test: /\.(png|jpg|svg)$/i,
                loader: 'file-loader'
            }
```

相关文章

  • Webpack深入与实战

    如果把项目开发的过程比作用积木搭房子的过程,Browserify:封装了各种各样的的小积木块,那怎么把这些积...

  • webpack深入与实战

    命令行 打包js 打包css首先安装依赖: css-loader 使webpack能处理.css文件。style-...

  • webpack深入到实战

    https://www.imooc.com/learn/802/

  • 深入koa源码(一):架构设计

    本文来自《心谭博客·深入koa源码:架构设计》前端面试、设计模式手册、Webpack4教程、NodeJs实战等更多...

  • webpack实战--webpack-dev-server介绍|

    实战最简单的webpack命令: npx webpack --entry=./index.js --output-...

  • Java书籍推荐

    《深入理解Java虚拟机:JVM高级特性与最佳实践》 ***** 《HotSpot实战》 《Java并发编程实战》...

  • webpack 原理与实战

    Ba la la la ~ 读者朋友们,你们好啊,又到了冷锋时间,话不多说,发车! webpack是什么...

  • rem、vw可伸缩布局框架(fpx)

    前言 前面我们分析了webpack,最后还实战了一个vue的项目: webpack实战之(手把手教你从0开始搭建一...

  • 电子书收藏

    深入浅出 Webpack

  • 书单

    技术书单 Java编程思想 深入理解Java虚拟机:JVM高级特性与最佳实践 HotSpot实战 Spring实战...

网友评论

      本文标题:webpack深入与实战

      本文链接:https://www.haomeiwen.com/subject/ltfzottx.html