目录
前面的话
版本号
模板文件
多页面
内联
babel
CSS
图片资源
实用配置
首页 web前端 js教程 详细介绍webpack实用配置

详细介绍webpack实用配置

Jun 24, 2017 pm 02:16 PM
web webpack 实用 配置

前面的话

  上文介绍了webpack入门,本文将详细介绍webpack实用配置

 

版本号

  以entry.js打包为bundle.js为例,出口的filename可以设置为[id]、[name]、[hash]、[chunkhash]等替换形式,如下所示

1

2

3

4

5

var webpack = require('webpack');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: '[id]-[name]-[hash].js'//出口名称  }

}

登录后复制

  则出口文件为0-main-0c1dce21f6c5db455fb4.js

  如果index.html要引用打包后的js文件,由于文件名称不确定,并不好解决。这时,就需要使用html-webpack-plugin插件。该插件并不是内置插件,所以需要安装

1

npm install html-webpack-plugin

登录后复制

  HtmlWebpackPlugin简化了HTML文件的创建,以便为webpack包提供服务。这对于在文件名中包含每次会随着变异会发生变化的哈希的webpack bundle尤其有用

1

2

3

4

5

6

7

8

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: '[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      title: 'match',//生成的html文件的标题为'match'  filename: 'index.html'//生成的html文件名称为'index.html'    })

  ]

}

登录后复制

  通过以上的配置,如果在当前路径,index.html不存在,则生成;如果存在,则替换

  [注意]如果htmlwebpackplugin不进行配置,参数为空, plugins: [new HtmlWebpackPlugin()]。默认地,生成的html文件名称为'index.html',标题为'Webpack APP' 

【标签位置】

  htmlwebpackplugin插件的常用设置是设置script标签插入的位置,默认插入到body标签中,但可以使用inject:'head',设置插入到head标签中

1

2

3

4

5

6

7

8

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      inject:'head',//将script标签插入到head标签中  filename: 'index-[hash].html',//生成的html文件名称为'index.html'    })

  ]

}

登录后复制

【图标设置】

  设置favicon属性,可以设置网页的小图标

1

2

3

4

5

6

7

8

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      favicon:'./icon.ico'})

  ]

}

登录后复制

【压缩】

  设置minify属性,可以压缩html文件,默认为false,即不压缩

1

2

3

4

5

6

7

8

9

10

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      minify:{

          removeComments: true,//删除注释  collapseWhitespace:true//删除空格      }

    })

  ]

}

登录后复制

  使用webpack打包后的index.html代码如下

1

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Webpack App</title></head><body><script type="text/javascript" src="js/0-main-8128c0c26a4449da7a05.js?1.1.11"></script></body></html>

登录后复制

 

模板文件

  HtmlWebpackPlugin除了提供模块版本号的功能,还可以使用模板文件

  例如,模板文件为template.html,内容如下

1

2

3

4

5

6

7

8

9

10

11

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>template</title>

</head>

<body>

<script src="test.js?1.1.11"></script>

<div>test</div>    

</body>

</html>

登录后复制

  webpack配置文件如下

1

2

3

4

5

6

7

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({  filename: 'index-[hash].html',//生成的html文件名称为'index.html'  template:'template/template.html'//模板文件为'template.html'    })

  ]

}

登录后复制

  生成的index-[hash].html以'template.html'文件为模板

  [注意]如果在htmlwebpackplugin中使用了模板,则指定title不会生效,因为要以模板的title为准  

1

2

3

4

5

6

7

8

9

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      title:'test',

      filename: 'index-[hash].html',//生成的html文件名称为'index.html'  template:'template/template.html'//模板文件为'template.html'    })

  ]

}

登录后复制

【传参】

  模块文件当然是可以传参的,一般地,使用ejs语法。例如,在模板文件中,使用<%= htmlWebpackPlugin.options.title %>,即可读取htmlWebpackPlugin插件中'title'属性的值

  [注意]模板文件中的'htmlWebpackPlugin'是固定的,不能随意更改。与webpack.config.js文件中,require()该插件的命名无关

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      title:'test',

      template:'template/template.html',//模板文件为'template.html'  dateData: new Date() 

    })

  ]

}//template.html<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title><%= htmlWebpackPlugin.options.title  %></title>

</head>

<body>

<div><%=htmlWebpackPlugin.options.dateData %></div>

</body>

</html>

登录后复制

【模板组件】

  下面利用模板组件组合成一个html文件,以ejs模板语言为例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      template:'template/template.html'})

  ]

}//template.html<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

</head>

<body>

<div>

    <% include  template/header.html %>

</div>

<ul>  

    <% var arr = [1,2,3,4,5] %>

    <% for(var i = 0; i < arr.length; i++){ %>  

        <li><%=arr[i] %></li>  

    <% } %>  

</ul>  

<div>

    <% include  template/footer.html %>

</div>

</body>

</html>//header.html<div>我是头部</div>//footer.html<div>我是尾部</div>

登录后复制

  运行结果报错,提示子模板加载失败

  这是因为HtmlWebpackPlugin插件并不具备ejs模板语言所有的功能,其中一个就是不能识别<%include %>语句,这时需要安装一个ejs-compiled-loader

1

npm install ejs-compiled-loader

登录后复制

  安装完成后,修改配置文件如下,表示使用ejs-compiled-loader来编译template.html

  [注意]该插件中的include路径相对于webpack配置文件的位置,而不是模板文件template.html的位置

1

2

3

4

5

6

7

8

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

      template:'ejs-compiled-loader!template/template.html'})

  ]

}

登录后复制

  结果如下

 

多页面

  对于多页面来说,一般地,有多个入口文件。不同的html页面输出对应不同的入口文件。 插件plugins()是一个数组,每new一个HtmlWebpackPlugin(),就可以输出一个html页面。这里有两个重要的属性:chunks和excludeChunks,chunks表示所包含的入口文件,excludeChunks表示要排除的入口文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: {

      a:'./src/js/a.js',

      b:'./src/js/b.js',

      c:'./src/js/c.js'

  },

  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

          filename:'a.html',

          template:'src/template/template.html',

          title:'this is a',

          chunks:['a']

    }),new HtmlWebpackPlugin({

          filename:'b.html',

          template:'src/template/template.html',

          title:'this is b',

          chunks:['b']

    }),new HtmlWebpackPlugin({

          filename:'c.html',

          template:'src/template/template.html',

          title:'this is c',

          excludeChunks:['a','b']

    }),    

  ]

}

登录后复制

  结果如下

1

//a.html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>this is a</title></head><body><div></div><script type="text/javascript" src="js/2-a-9828ea84bd8c12c19b5f.js?1.1.11"></script></body></html>//b.html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>this is b</title></head><body><div></div><script type="text/javascript" src="js/1-b-9828ea84bd8c12c19b5f.js?1.1.11"></script></body></html>//c.html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>this is c</title></head><body><div></div><script type="text/javascript" src="js/0-c-9828ea84bd8c12c19b5f.js?1.1.11"></script></body></html>

登录后复制

 

内联

  在前面的例子中,都是以链接的形式引入入口文件的。有时,为了追求性能,会将其处理为内联的形式。这里就需要安装一个扩展插件html-webpack-inline-source-plugin,专门用来处理入口文件内联的

1

$ npm install --save-dev html-webpack-inline-source-plugin

登录后复制

  该插件的使用很简单,使用require()语句引入后,在插件plugins()新建一个html-webpack-inline-source-plugin对象,然后在html-webpack-plugin对象中添加inlineSource属性即可

1

inlineSource: '.(js|css)$' // embed all javascript and css inline

登录后复制

1

2

3

4

5

6

7

8

9

10

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');

 

module.exports = {

  entry: './entry.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  plugins: [new HtmlWebpackPlugin({

        inlineSource: '.(js|css)$'}),new HtmlWebpackInlineSourcePlugin()

  ]

}

登录后复制

  结果如下

1

2

3

4

5

6

7

8

9

10

11

<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8">

    <title>Webpack App</title>

  </head>

  <body>

  <script type="text/javascript">/******/ (function(modules) { // webpackBootstrap/******/     // The module cache/******/     var installedModules = {};/******//******/     // The require function/******/     function __webpack_require__(moduleId) {/******//******/         // Check if module is in cache/******/         if(installedModules[moduleId]) {/******/             return installedModules[moduleId].exports;/******/         }/******/         // Create a new module (and put it into the cache)/******/         var module = installedModules[moduleId] = {/******/             i: moduleId,/******/             l: false,/******/             exports: {}/******/         };/******//******/         // Execute the module function/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);/******//******/         // Flag the module as loaded/******/         module.l = true;/******//******/         // Return the exports of the module/******/         return module.exports;/******/     }/******//******//******/     // expose the modules object (__webpack_modules__)/******/     __webpack_require__.m = modules;/******//******/     // expose the module cache/******/     __webpack_require__.c = installedModules;/******//******/     // identity function for calling harmony imports with the correct context/******/     __webpack_require__.i = function(value) { return value; };/******//******/     // define getter function for harmony exports/******/     __webpack_require__.d = function(exports, name, getter) {/******/         if(!__webpack_require__.o(exports, name)) {/******/             Object.defineProperty(exports, name, {/******/                 configurable: false,/******/                 enumerable: true,/******/                 get: getter/******/             });/******/         }/******/     };/******//******/     // getDefaultExport function for compatibility with non-harmony modules/******/     __webpack_require__.n = function(module) {/******/         var getter = module && module.__esModule ?/******/             function getDefault() { return module['default']; } :/******/             function getModuleExports() { return module; };/******/         __webpack_require__.d(getter, 'a', getter);/******/         return getter;/******/     };/******//******/     // Object.prototype.hasOwnProperty.call/******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };/******//******/     // __webpack_public_path__/******/     __webpack_require__.p = "";/******//******/     // Load entry module and return exports/******/     return __webpack_require__(__webpack_require__.s = 0);/******/ })/************************************************************************//******/ ([/* 0 *//***/ (function(module, exports) {

 

document.write('It works.')/***/ })/******/ ]);</script></body>

</html>

登录后复制

 

babel

  下面使用babel来进行es最新标准的代码向es5代码的转换,首先需要安装babel核心程序,及babel-loader

1

npm install babel-loader babel-core

登录后复制

  在使用babel-loader进行代码转换之前,要先了解到ecmascript标准变化很快,且浏览器支持情况不同。所以,出现了'es2015'、'es2016'、'es2017'、'latest'、'env(new)'等多个不同的标准。这时,要需要来选择从哪个标准进行转换,需要安装插件babel-preset-env 

1

npm install babel-preset-env

登录后复制

  在 webpack 配置对象中,需要添加 babel-loader 到 module 的 loaders 列表中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

 

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      loaders:[{

          test:/\.js$/,

          use:{

              loader:'babel-loader',

              options:{

                  presets: ['env']

              }

          }

      }]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

1

2

//app.jslet num = 1;

console.log(num);

登录后复制

【打包速度】

  运行后,页面控制台输出1,转换正常。但是,babel的转换过程却很慢

  前面的博文webpack的四个基本概念,我们介绍过loader的test属性表示该loader必须满足的条件,上面代码中使用/\.js$/ 来匹配,这样也许会去转译 node_modules 目录或者其他不需要的源代码。这样会大大增加webpack的编译时间

  要排除 node_modules,就要使用 loaders 配置的 exclude 选项,表示哪些除外,exclude:/node_modules/

  [注意]exclude也应该用正则的形式,如果用__dirname +'/node_modules'的形式则不会生效

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

 

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      loaders:[{

          test:/\.js$/,

          exclude: /node_modules/,

          use:{

              loader: 'babel-loader',

              options:{

                  presets: ['env']

              }

          }

      }]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

  当然了,除了exclude选项,也有include选项,能够明确被打包的文件时,使用include将使打包速度更快

  对于include来说,它比较特别,字符串形式__dirname + './src/'和正则形式/\.\/src/都支持,经过测试,这两种形式的打包速度类似

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

 

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      loaders:[{

          test:/\.js$/,

          include:/\.\/src/,

          use:{

              loader: 'babel-loader',

              options:{

                  presets: ['env']

              }

          }

      }]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

 

CSS

  在webpack入门博文中由介绍过CSS插件的简单使用,接下来将详细介绍

  首先,要安装css-loader和style-loader,css-loader用于读取并加载css文件,style-loader将它插入到页面中

  [特别注意]在处理css时,最好不要使用include、exclude等属性。include、exclude属性是加快babel转换速度的,和css没什么关系,而且会添乱

1

npm install css-loader style-loader

登录后复制

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//app.jsrequire('./css/common.css');//common.cssbody{margin: 0;background-color: red}//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,  use:[ 'style-loader''css-loader' ]

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

  效果如下

【自动前缀】

  页面加载CSS往往并不像上面的情况这么简单,需要处理很多问题,其中一个就是浏览器前缀问题。对于某些属性来说,比如transform,不同浏览器的版本对其支持程度不同,浏览器前缀也不同。这时,就需要能够根据实际情况,自动增加前缀,而postcss-loader就是这样的工具,而且功能要强大的多

  首先,先安装postcss-loader

1

npm install postcss-loader

登录后复制

  然后,安装postcss的自动前缀的插件autoprefixer

1

npm install autoprefixer

登录后复制

  配置如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

//common.cssbody{transform: scale(0);background-color: red}//app.jsrequire('./css/common.css');//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader''css-loader',                    

                    {

                        loader: 'postcss-loader',

                        options: {plugins: [require('autoprefixer')]}            

                    }

                 ]

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

  结果如下

  如果css文件中出现@import,则有两种处理方式,一种是将postcss文件单独写成配置文件postcss.config.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

//common.css@import './flex.css';

body{transform: scale(0);background-color: red}//flex.cssbody{display:flex;}//app.jsrequire('./css/common.css');//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader'

                  { loader: 'css-loader',

                    options: {importLoaders: 1} 

                  },'postcss-loader']

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}//postcss.config.jsmodule.exports = {

 plugins:[require('autoprefixer')]

}

登录后复制

  结果如下

  另一种需要安装postcss-import插件

1

npm install postcss-import

登录后复制

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

//common.css@import './flex.css';

body{transform: scale(0);background-color: red}//flex.cssbody{display:flex;}//app.jsrequire('./css/common.css');//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader'

                  { loader: 'css-loader',

                    options: {importLoaders: 1 } 

                  },

                  {

                    loader: 'postcss-loader',

                    options: {plugins: [

                          require('postcss-import'),

                          require('autoprefixer')

                        ]

                    }     

                  }

                ]

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

  结果如下

【sass】

  首先,需要安装sass-loader及node-sass

   [注意]关于node-sass安装的问题移步至此

1

npm install sass-loader node-sass

登录后复制

  由于sass-loader中已经自带了关于@import处理的问题。所以,不需要css-loader及postcss-loader的额外处理

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

//layer.scss@import './flex.scss';

body{

    background-color:green;

    div{

        width: 400px;

    }

}//flex.scss.flex{display:flex;}//app.jsrequire('./components/layer/layer.scss');//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.scss$/,

              use:[    'style-loader'

                      'css-loader',

                    {

                        loader: 'postcss-loader',

                        options: {plugins: [require('autoprefixer')]}            

                    },'sass-loader' ]

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({})

  ]

}

登录后复制

  结果如下

【分离CSS】

  默认地,CSS作为模块资源被打包到入口js文件中。有时,需要把CSS文件分离出来,这时就需要用到extract-text-webpack-plugin插件

1

npm install extract-text-webpack-plugin

登录后复制

  该插件的配置如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

  entry: './src/app.js',

  output:{

    path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称  },

  module:{

      rules:[

          {

                  test:/\.scss$/,

                use: ExtractTextPlugin.extract({

                  fallback: 'style-loader',

                  use:[ 'css-loader',

                        {

                            loader: 'postcss-loader',

                            options: {plugins: [require('autoprefixer')]}            

                        },'sass-loader' ]

                })              

          }

      ]

  },

  plugins: [new HtmlWebpackPlugin({}),new ExtractTextPlugin("styles.css?1.1.11")

  ]

}

登录后复制

  结果如下,该插件将入口文件中引用的 *.css,移动到独立分离的 CSS 文件。因此,你的样式将不再内嵌到 JS bundle 中,而是会放到一个单独的 CSS 文件(即 styles.css)当中。 如果样式文件大小较大,这会做更快提前加载,因为 CSS bundle 会跟 JS bundle 并行加载

 

 

图片资源

  webpack在处理图片、音乐、电影等资源文件时,需要使用file-loader

1

npm install file-loader

登录后复制

  默认情况下,使用file-loader生成的文件的文件名就是文件内容的MD5哈希值并保留原始扩展名

  以引入图片资源例,有以下几种情况

  1、通过css文件的background属性引入

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  module:{

 

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader''css-loader' ]

          },

          {

              test:/\.(png|jpg|gif|svg)$/i,

              use:'file-loader'  }

      ]

  },  

  plugins: [new HtmlWebpackPlugin()

  ]

}//entry.jsrequire('./src/css/common.css');//common.cssbody{background: url('../img/eg_bulbon.gif')}

登录后复制

  结果如下

  2、通过模板html文件img标签引入,这时需要使用${require('')}将相对路径包裹一次

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname,//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader''css-loader' ]

          },

          {

              test:/\.(png|jpg|gif|svg)$/i,

              use:'file-loader'  }

      ]

  },  

  plugins: [new HtmlWebpackPlugin({

        template:'template/template.html'})

  ]

}//template.html<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

</head>

<body>

<img src="${require(&#39;../src/img/eg_bulbon.gif&#39;)}" alt="">

</body>

</html>

登录后复制

  结果如下

  3、若模板使用ejs-compiled-loader插件,则无法使用${require('')}语句,需要使用HtmlWebpackPlugin传参来构造绝对路径

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

//webpack.config.jsvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  entry: './entry.js'//入口文件  output: {

    path: __dirname + '/dist',//出口路径filename: 'js/[id]-[name]-[hash].js'//出口名称  },

  module:{

      rules:[

          {

              test:/\.css$/,

              use:[ 'style-loader''css-loader' ]

          },

          {

              test:/\.(png|jpg|gif|svg)$/i,

              use:'file-loader'  }

      ]

  },  

  plugins: [new HtmlWebpackPlugin({

        template:'ejs-compiled-loader!template/template.html',

        file:__dirname

    })

  ]

}//template.html<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

</head>

<body>

<div>

    <% include  template/header.html %>

</div>

</body>

</html>//header.html<img src="<%=htmlWebpackPlugin.options.file%>\src\img\eg_bulbon.gif" alt="">

登录后复制

  结果如下

【file-loader参数】

  文件名模板占位符有如下几种

1

2

3

4

5

6

7

8

9

[ext] 资源扩展名

[name] 资源的基本名称

[path] 资源相对于 context 查询参数或者配置的路径

[hash] 内容的哈希值,默认为十六进制编码的 md5

[<hashType>:hash:<digestType>:<length>] 可选配置

  其他的 hashType, 即 sha1, md5, sha256, sha512

  其他的 digestType, 即 hex, base26, base32, base36, base49, base52, base58, base62, base64

  length 字符的长度

[N] 当前文件名按照查询参数 regExp 匹配后获得到第 N 个匹配结果

登录后复制

1

2

3

4

5

6

7

8

{

  test:/\.(png|jpg|gif|svg)$/i,

  use:[{

              loader:'file-loader',

            options: {

                name:'[name]-[hash:5].[ext]'}  

        }]

}

登录后复制

  或者

1

2

3

4

{

  test:/\.(png|jpg|gif|svg)$/i,

  use:['file-loader?name=[name]-[hash:5].[ext]']

}

登录后复制

  结果如下

【url-loader】

  url-loader功能类似于file-loader,但是在文件大小(单位byte)低于指定的限制时,可以返回一个dataURL

  可以通过传递查询参数(query parameter)来指定限制(默认为不限制)。

  如果文件大小超过限制,将转为使用 file-loader,所有的查询参数也会传过去

1

npm install url-loader

登录后复制

  图片的大小为1.1kb,下面将限制设置为2000,则图片将以base64格式传递

1

2

3

4

{

  test:/\.(png|jpg|gif|svg)$/i,

  use:['url-loader?limit=2000']

}

登录后复制

  结果如下

  如果将限制大小设置为1000,图片以src的形式传递

1

2

3

4

5

6

7

8

9

{

  test:/\.(png|jpg|gif|svg)$/i,

  use:[{

              loader:'url-loader',

            options: {

                limit:1000,

                name:'[name]-[hash:5].[ext]'}  

        }]

}

登录后复制

【image-webpack-loader】

  使用image-webpack-loader来压缩图片

1

npm install image-webpack-loader

登录后复制

  插件一张大小为4.1kb的名称为'm.jpg'的图片,配置如下

1

2

3

4

5

{

  test:/\.(png|jpg|gif|svg)$/i,

  use:['url-loader?limit=1000&name=[name]-[hash:5].[ext]','image-webpack-loader'

  ]

}

登录后复制

  结果如下所示,生成大小为3.28kb,名称为'm-c7083.jpg'的图片

 

实用配置

  下面将使用webpack搭建一个实用的开发环境

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

    entry: './src/app.js',//入口文件    output:{

        path: __dirname,//出口路径filename: 'js/[name].bundle.js'//出口名称    },

    module:{

        rules:[

            {

                test:/\.scss$/,

                use: ExtractTextPlugin.extract({

                    fallback: 'style-loader',

                     use:[ 

                             'css-loader',

                            {

                                loader: 'postcss-loader',//自动添加前缀options: {plugins: [require('autoprefixer')]}            

                            },'sass-loader']

                })              

            },

            {

                test:/\.js$/,

                include:/\.\/src/,

                use:{

                        loader: 'babel-loader',//将最新标准的js代码翻译为es5代码options:{presets: ['env']}

                    }

            },

            {

                test:/\.(png|jpg|gif|svg)$/i,

                use:[//当图片大小大于1000byte时,以[name]-[hash:5].[ext]的形式输出//当图片大小小于1000byte时,以baseURL的形式输出'url-loader?limit=1000&name=[name]-[hash:5].[ext]',//压缩图片'image-webpack-loader']

            }

          ]

    },

    plugins: [          //使用模板生成html文件new HtmlWebpackPlugin({template:'ejs-compiled-loader!template/template.html'}),//分离出css到style.cssnew ExtractTextPlugin("style.css?1.1.11")

    ]

}

登录后复制

 

 

 

 

 

以上是详细介绍webpack实用配置的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1675
14
CakePHP 教程
1429
52
Laravel 教程
1333
25
PHP教程
1278
29
C# 教程
1257
24
Linux系统中GDM的工作原理及配置方法 Linux系统中GDM的工作原理及配置方法 Mar 01, 2024 pm 06:36 PM

标题:Linux系统中GDM的工作原理及配置方法在Linux操作系统中,GDM(GNOMEDisplayManager)是一种常见的显示管理器,用于控制图形用户界面(GUI)登录和用户会话管理。本文将介绍GDM的工作原理和配置方法,以及提供具体的代码示例。一、GDM的工作原理GDM是GNOME桌面环境下的显示管理器,负责启动X服务器并提供登录界面,用户输

PyCharm新手指南:学会在PyCharm中删除项目 PyCharm新手指南:学会在PyCharm中删除项目 Feb 23, 2024 pm 09:39 PM

PyCharm新手指南:删除项目的实用技巧PyCharm是一款功能强大的Python集成开发环境(IDE),在进行项目开发时,有时候需要删除项目或项目中的文件。本文将介绍在PyCharm中删除项目的实用技巧,并提供具体的代码示例帮助新手更好地理解和应用。1.删除项目删除项目意味着删除整个项目文件夹,这在我们需要清理或重建项目时非常有用。在PyCharm中删

全角英文字母转换为半角形式的实用技巧 全角英文字母转换为半角形式的实用技巧 Mar 26, 2024 am 09:54 AM

全角英文字母转换为半角形式的实用技巧在现代生活中,我们经常会接触到英文字母,在使用电脑、手机等设备时也经常需要输入英文字母。然而,有时候我们会遇到全角英文字母的情况,而我们需要使用的是半角形式。那么,如何将全角英文字母转换为半角形式呢?下面就为大家介绍一些实用的技巧。首先,全角英文字母和数字是指在输入法中占据一个全角位置的字符,而半角英文字母和数字则是占据一

了解Linux Bashrc:功能、配置与使用方法 了解Linux Bashrc:功能、配置与使用方法 Mar 20, 2024 pm 03:30 PM

了解LinuxBashrc:功能、配置与使用方法在Linux系统中,Bashrc(BourneAgainShellruncommands)是一个非常重要的配置文件,其中包含了系统启动时自动运行的各种命令和设置。Bashrc文件通常位于用户的家目录下,是一个隐藏文件,它的作用是为用户自定义设置Bashshell的环境。一、Bashrc的功能设置环境

win11系统如何配置工作组 win11系统如何配置工作组 Feb 22, 2024 pm 09:50 PM

Win11系统如何配置工作组工作组是一种在局域网中连接多台计算机的方式,它允许计算机之间共享文件、打印机和其他资源。在Win11系统中,配置工作组非常简单,只需按照以下步骤操作即可。步骤1:打开“设置”应用程序首先,点击Win11系统的“开始”按钮,然后在弹出的菜单中选择“设置”应用程序。你也可以使用快捷键“Win+I”打开“设置”。步骤2:选择“系统”在“设置”应用程序中,你会看到多个选项。请点击“系统”选项,进入系统设置页面。步骤3:选择“关于”在“系统”设置页面中,你会看到多个子选项。请点

Linux系统中如何配置和安装FTPS Linux系统中如何配置和安装FTPS Mar 20, 2024 pm 02:03 PM

标题:Linux系统中如何配置和安装FTPS,需要具体代码示例在Linux系统中,FTPS是一种安全的文件传输协议,与FTP相比,FTPS通过TLS/SSL协议对传输的数据进行加密,提高了数据传输的安全性。在本文中,将介绍如何在Linux系统中配置和安装FTPS,并提供具体的代码示例。步骤一:安装vsftpd打开终端,输入以下命令安装vsftpd:sudo

MyBatis Generator配置参数解读及最佳实践 MyBatis Generator配置参数解读及最佳实践 Feb 23, 2024 am 09:51 AM

MyBatisGenerator是MyBatis官方提供的一个代码生成工具,可以帮助开发人员快速生成符合数据库表结构的JavaBean、Mapper接口以及XML映射文件。在使用MyBatisGenerator进行代码生成的过程中,配置参数的设置是至关重要的。本文将从配置参数的角度出发,深入探讨MyBatisGenerator的

CentOS7系统安装和配置 DRBD?实现高可用性和数据冗余教程! CentOS7系统安装和配置 DRBD?实现高可用性和数据冗余教程! Feb 22, 2024 pm 02:13 PM

DRBD(DistributedReplicatedBlockDevice)是一种用于实现数据冗余和高可用性的开源解决方案。下面是在CentOS7系统上安装和配置DRBD的教程:安装DRBD:打开终端并以管理员身份登录到CentOS7系统。运行以下命令以安装DRBD软件包:sudoyuminstalldrbd配置DRBD:编辑DRBD配置文件(通常位于/etc/drbd.d目录下),配置DRBD资源的设置。例如,可以定义主节点和备份节点的IP地址、端口和设备等。确保主节点和备份节点之间可以通过网

See all articles