GVKun编程网logo

webpack学习(四)extract-text-webpack-plugin插件(webpack 常用插件)

12

在本文中,我们将带你了解webpack学习在这篇文章中,我们将为您详细介绍webpack学习的方方面面,并解答四extract-text-webpack-plugin插件常见的疑惑,同时我们还将给您一

在本文中,我们将带你了解webpack学习在这篇文章中,我们将为您详细介绍webpack学习的方方面面,并解答四extract-text-webpack-plugin插件常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的645 webpack常用plugins:clean-webpack-plugin,html-webpack-plugin,webpack.DefinePlugin,copy-webpack-plug、css文件实现分离的插件(extract-text-webpack-plugin)的用法、extract-text-webpack-plugin 打包css报错的解决、extract-text-webpack-plugin 的使用及安装

本文目录一览:

webpack学习(四)extract-text-webpack-plugin插件(webpack 常用插件)

webpack学习(四)extract-text-webpack-plugin插件(webpack 常用插件)

二、extract-text-webpack-plugin插件

从 bundle 中提取文本(CSS)到单独的文件

安装

npm install extract-text-webpack-plugin --save-dev 

 用法

var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

 它会将所有的入口 chunk(entry chunks)中引用的 *.css,移动到独立分离的 CSS 文件。

因此,你的样式将不再内嵌到 JS bundle 中,而是会放到一个单独的 CSS 文件(即 styles.css)当中。

如果你的样式文件大小较大,这会做更快提前加载,因为 CSS bundle 会跟 JS bundle 并行加载。

 

645 webpack常用plugins:clean-webpack-plugin,html-webpack-plugin,webpack.DefinePlugin,copy-webpack-plug

645 webpack常用plugins:clean-webpack-plugin,html-webpack-plugin,webpack.DefinePlugin,copy-webpack-plug

-

  • 前端小菜鸟,喜欢前端,不断学习
  • 微信:jie178463596
  • 微信小群:纯粹讨论技术、面试、工作为主,划水少,拒绝广告

认识Plugin


CleanWebpackPlugin


HtmlWebpackPlugin


生成的index.html分析


自定义HTML模板


自定义模板数据填充


DefinePlugin的介绍


DefinePlugin的使用


copyWebpackPlugin


目录结构


wk.config.js

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { DefinePlugin } = require('webpack'); // DefinePlugin是webpack内置插件
const copyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: "./src/main.js",
  output: {
    filename: "js/bundle.js",
    // 必须是一个绝对路径
    path: path.resolve(__dirname, "./build"),
    // assetmodulefilename: "img/[name].[hash:6][ext]"
  },
  module: {
    rules: [
      {
        // 规则使用正则表达式
        test: /\.css$/, // 匹配资源
        use: [
          // { loader: "css-loader" },
          // 注意: 编写顺序(从下往上, 从右往做, 从后往前)
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 1
            }
          },
          "postcss-loader"
        ],
        // loader: "css-loader"
      },
      {
        test: /\.less$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 2
            }
          },
          "postcss-loader",
          "less-loader"
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        // type: "asset/resource", file-loader的效果
        // type: "asset/inline", url-loader
        type: "asset",
        generator: {
          filename: "img/[name].[hash:6][ext]"
        },
        parser: {
          dataUrlCondition: {
            maxSize: 100 * 1024
          }
        }
      },
      {
        test: /\.ttf|eot|woff2?$/i,
        type: "asset/resource",
        generator: {
          filename: "font/[name].[hash:6][ext]"
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: "哈哈 webpack",
      template: "./public/index.html"
    }),
    new DefinePlugin({
      // 要包裹两层引号
      BASE_URL: '"./"'
    }),
    new copyWebpackPlugin({
      patterns: [
        {
          // to: xxx, // 不用写,默认会使用output.path
          from: "public",
          globOptions: {
            ignore: [
              "**/index.html",
              "**/.DS_Store",
              "**/abc.txt"
            ]
          }
        }
      ]
    })
  ]
}


publuc/index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <Meta charset="utf-8">
    <Meta http-equiv="X-UA-Compatible" content="IE=edge">
    <Meta name="viewport" content="width=device-width,initial-scale=1.0">
    
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

build/index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <Meta charset="utf-8">
    <Meta http-equiv="X-UA-Compatible" content="IE=edge">
    <Meta name="viewport" content="width=device-width,initial-scale=1.0">
    
    <link rel="icon" href="./favicon.ico">
    
    <title>杰帅的webpack</title>
  <script defer src="js/bundle.js"></script></head>
  <body>
    <noscript>
      <strong>We're sorry but 杰帅的webpack doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

css文件实现分离的插件(extract-text-webpack-plugin)的用法

css文件实现分离的插件(extract-text-webpack-plugin)的用法

本篇文章给大家带来的内容是关于css文件实现分离的插件(extract-text-webpack-plugin)的用法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

css分离:extract-text-webpack-plugin

1、安装该插件:

for webpack 1 npm install –save-dev extract-text-webpack-plugin@1.0.1 for webpack 2 npm install –save-dev extract-text-webpack-plugin@2.1.2 for webpack 3 npm install –save-dev extract-text-webpack-plugin for webpack 4 npm i extract-text-webpack-plugin@next -D

2、在webpack-config.js中引入插件
 const extractTextPlugin=require(“extract-text-webpack-plugin”);

3、配置plugins:这里new一下这个对象,与上面那个配置插件用逗号分隔
 new extractTextPlugin(“/css/index,.css”)

4、这里的/css/index.css是分离后的路径位置。这部配置完成后,包装代码:还要修改原来我们的style-loader和css-loader

    • [x] 修改代码如下:

      module:{        rules: [
                  {
                    test: /\.css$/,
                    use: extractTextPlugin.extract({
                      fallback: "style-loader",
                      use: "css-loader"
                    })
                  },{               test:/\.(png|jpg|gif)/ ,
                     use:[{
                         loader:&#39;url-loader&#39;,
                         options:{
                             limit:500000
                         }
                     }]
                  }
                ]
          },
      登录后复制

      5、使用webpack进行打包

      立即学习“前端免费学习笔记(深入)”;

    • publicPath:是在webpack.config.js文件的output选项中,主要作用就是处理静态文件路径的

    • 在处理前需要在webpack.config.js上方声明一个website对象

    • 注意:这里的IP和端口是本机的ip或者是你devServer配置的IP和端口 //==publicPath里面的内内容一定要写正确:用ipconfig查看电脑的ip地址,然后冒号后面跟自己设置的端口==

    • 注意:虽然把css文件分离出来了,但是css路径不对

    • 用==publishPath==来解决

      var website={
          publicPath:"http://192.168.1.108:1717"}
      登录后复制

      6、在output选项中引用这个对象的publicPath属性

      //出口文件的配置项output:{    //输出的路径,用了Node语法
          path:path.resolve(__dirname,&#39;dist&#39;),    //输出的文件名称
          filename:&#39;[name].js&#39;,
          publicPath:website.publicPath
      },
      登录后复制

      7、使用webpack进行打包,这时原来的相对路径就会变为绝对路径(绝对路径速度会更快)

    *若出现下列错误,说明ip没写对

    > y@1.0.0 server F:\webLearn\webpackLearn
    > webpack-dev-server
    
    events.js:183
          throw er; // Unhandled &#39;error&#39; event
          ^
    
    Error: listen EADDRNOTAVAIL 10.212.109.18:8087
        at Object._errnoException (util.js:992:11)    at _exceptionWithHostPort (util.js:1014:20)    at Server.setupListenHandle [as _listen2] (net.js:1338:19)    at listenInCluster (net.js:1396:12)    at doListen (net.js:1505:7)    at _combinedTickCallback (internal/process/next_tick.js:141:11)    at process._tickCallback (internal/process/next_tick.js:180:9)    at Function.Module.runMain (module.js:695:11)    at startup (bootstrap_node.js:191:16)    at bootstrap_node.js:612:3npm ERR! code ELIFECYCLE
    npm ERR! errno 1npm ERR! y@1.0.0 server: `webpack-dev-server`
    npm ERR! Exit status 1npm ERR!
    npm ERR! Failed at the y@1.0.0 server script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\勾丽娜\AppData\Roaming\npm-cache\_logs\2018-07-11T07_46_12_914Z-debug.logPS F:\webLearn\webpackLearn>
    登录后复制

    修改好正确的ip地址就可以运行成功了,哈哈

    相关推荐:

    css文件如何进行打包?css文件打包的方法

    html文件如何打包 ?html文件打包的方法介绍

    以上就是css文件实现分离的插件(extract-text-webpack-plugin)的用法的详细内容,更多请关注php中文网其它相关文章!

    extract-text-webpack-plugin 打包css报错的解决

    extract-text-webpack-plugin 打包css报错的解决

    全局安装的webpack版本是v4.12.1,但是package.json引用的webpack版本是v3.6.0,install下来/node_modules/里面webpack版本是v3.12.0。
    在控制台输入webpack -v,得到的结果是4.12.1。
    这是webpack环境。

    开始引入extract-text-webpack-plugin,默认的版本是v3.0.2,运行webpack报错:

    $ webpack
    (node:18800) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
    C:\Users\EEE\AppData\Roaming\npm\node_modules\webpack\lib\Chunk.js:752
                    throw new Error(
                    ^
    
    Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
    

    找了很多文章,都说是版本问题,下载了extract-text-webpack-plugin 4.0.0-beta.0版本,运行还是报错:

    $ webpack
    C:\Users\EEE\Desktop\webpack\node_modules\_extract-text-webpack-plugin@4.0.0-beta.0@extract-text-webpack-plugin\dist\index.js:217
                extractedChunk.addGroup(chunkGroup);
                               ^
    
    TypeError: extractedChunk.addGroup is not a function

    猜想会不会是webpack版本也需要升级,我删掉了package.json引用的webpack,打算使用全局webpack。
    重新install,运行webpack,还是报错:

    $ webpack
    C:\Users\EEE\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:244
                                    throw err;
                                    ^
    
    Error: Cannot find module ''webpack/lib/Chunk''

    似乎必须要引入webpack,在package.json再次引webpack,v4.12.0。
    得到的/node_modules/下的webpack版本是v4.26.1。
    再次执行webpack,这次成功了。

    这是一次很简单的采坑,但是前后困扰了我好几天。
    附配置文件:

    webpack.config.js

    const path = require(''path'');
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    
    module.exports = {
        entry: ''./src/index.js'',
        output: {
            path: path.resolve(__dirname, ''dist''),
            publicPath: ''/dist/'',
            filename: ''bundle.js''
        },
        mode: ''production'',
        module: {
          rules: [
            {
              test: /\.css$/,
              //loader: [''style-loader'',''css-loader'']
              use: ExtractTextPlugin.extract({
                fallback: "style-loader",
                use: "css-loader"
              })
            },
            {
              test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
              loader: ''url-loader'',
              options: {
                limit: 10000*4,
                name: ''[name].[ext]?[hash]''
              }
            }
          ]
        },
        plugins: [
          new ExtractTextPlugin("styles.css"),
        ]
    };

    package.json

    {
      "devDependencies": {
        "css-loader": "^0.28.7",
        "extract-text-webpack-plugin": "^4.0.0-beta.0",
        "file-loader": "^1.1.4",
        "style-loader": "^0.23.1",
        "url-loader": "^0.5.8",
        "webpack": "^4.12.0"
      }
    }

    extract-text-webpack-plugin 的使用及安装

    extract-text-webpack-plugin 的使用及安装

    extract-text-webpack-plugin该插件的主要是为了抽离css样式,防止将样式打包在js中引起页面样式加载错乱的现象;首先我先来介绍下这个插件的安装方法:

    npm i extract-text-webpack-plugin -D
    

    首先进入项目的根目录,然后执行以上命令进行插件的安装,插件安装完成后,接下来我们要做的就是在webpack.config.js中引入该插件

    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              fallback: "style-loader",
              use: "css-loader"
            })
          }
        ]
      },
      plugins: [
        new ExtractTextPlugin("styles.css"),
      ]
    }
    

    该插件有三个参数意义分别如下

    use:指需要什么样的loader去编译文件,这里由于源文件是.css所以选择css-loader
    fallback:编译后用什么loader来提取css文件
    publicfile:用来覆盖项目路径,生成该css文件的文件路径
    

    webpack打包报错Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

    **webpack打包环境优化的一个点:将css样式代码抽离出来。 **

    若不抽离,可以在bundle.js中发现css代码被转化成节点样式插入到了body下;这个过程是:style-loader将外部css文件注入到html中,css内容使用css-loader进行解析,转化成js文件;因为webpack只能识别js文件。

    css分离:

    使用extract-text-webpack-plugin插件,该插件的主要是为了抽离css样式,防止将样式打包在js中引起页面样式加载错乱的现象。

    **优点 **

    非js文件单独打包,通过js将文件写入,可以用来单独做浏览器缓存。 目前工程中大部分用到的还是webpack3+;实际中,在不指定版本的情况下,npm默认安装的4.0.0版本,这时使用上述插件会报错: Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

    **原因: **

    extract-text-webpack-plugin还不能支持webpack4.0.0以上的版本。

    **解决办法: **

    npm install –save-dev extract-text-webpack-plugin@next 会下载到+ extract-text-webpack-plugin@4.0.0-beta.0 然后在打包就正常了

    我们今天的关于webpack学习四extract-text-webpack-plugin插件的分享就到这里,谢谢您的阅读,如果想了解更多关于645 webpack常用plugins:clean-webpack-plugin,html-webpack-plugin,webpack.DefinePlugin,copy-webpack-plug、css文件实现分离的插件(extract-text-webpack-plugin)的用法、extract-text-webpack-plugin 打包css报错的解决、extract-text-webpack-plugin 的使用及安装的相关信息,可以在本站进行搜索。

    本文标签: