美文网首页
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深入与实战

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