webpack 3.11.0

2018-05-18  本文已影响0人  R_X

一、devServer

1、热更新 --- hot: true

在 webpack.config.js 中添加:

devServer: {
  hot: true
}

时,启动时会报:

会报:[HMR] Hot Module Replacement is disabled。

可以在 package.json 的 scripts 中用一下代码替代:

"scripts": {
  "start:dev": "webpack-dev-server --hot --inline"   
}

2、webpack-dev-server 版本问题

使用 3.*版本会有报错,可以改为 ^2.11.1

二、对于图片的处理

## webpack.comfig.js  --  module.rules中添加:
{
    test: /\.(png|jpeg|gif)$/,
    use: [
      // [path]:表示使用原有的路径; 也可以直接写死一个目录如:images/[name].[ext]?qing=[hash:8]
      // ?qing=[hash:8]:构建出来的图片名字不变,但是浏览器查看文件路径的时候,会在文件名字后面加上:?qing=12345678
      // 如果不在[ext]后面加参数,而是这样加:[path][name]-[hash:8].[ext],那么 不光构建后文件名字会变,浏览器端图片名字也会变。
      'url-loader?limit=133120&name=[path][name].[ext]?qing=[hash:8]',
      'img-loader',   
    ]
}

1、js 中引用图片

import imgUrl from './resource/qzx.jpeg'
const _img = document.createElement('IMG');
_img.setAttribute('src', imgUrl);
$('app').appendChild(_img);

2、 css 中引用图片

background-image: url('../src/resource/qzx.jpeg');

三、对于CSS的处理

在 modules.rules 中添加:

{
  test: /\.css$/,
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      { loader: 'css-loader', options: { importLoaders: 1 } },
      'postcss-loader'
    ]
  })
},

注意: 使用 postcss-loader 时,需要在项目根目录添加文件:postcss.config.js,可只导出空对象:module.exports = {};

四、webpack.config.js

const webpack = require('webpack'); // 用于访问内置插件
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const config = {
  // 单文件入口写法
  /* entry: './src/app.js', 
  output: {
    path: path.resolve(__dirname, 'build/dist'),
    filename: 'my-first-webpack.bundle.js'
  }, */
  // 多个入口点的写法:
  entry: {
    app: './src/app.js',
    vendor: ['jquery'],
    libs: ['./lib/lib01.js','./lib/lib02.js','./lib/lib03.js'],
  },
  output: {
    filename: '[name].[hash].js',
    path: path.resolve(__dirname, 'build/dist'),
    /**
     * publicPath: 如果开启了该配置,webpack会在生成的html中引入 entry中的文件js时,加上该配置项指定的路径。
     * 例子:
     *  不加时: <script src="app.123456876543.js">
     *  加了 publicPath: 'assets/'时: <script src="assets/app.12345654321.js">
     */
    // publicPath: 'assets/'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        // 这里想要成功的话需要安装 babel-core 依赖包。
        use: 'babel-loader'
      },
      { test: /\.txt$/, use: 'raw-loader' },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                importLoaders: 1,
                minimize: true, // 压缩 CSS 文件
              }
            },
            'postcss-loader'
          ]
        })
      },
      {
        test: /\.(png|jpeg|gif)$/,
        use: [
          'url-loader?limit=13312&name=[path][name].[hash].[ext]',
          'image-webpack-loader', // 图片压缩
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      uglifyOptions: {
        // 压缩优化
        compress: {
          warnings: false,  // 当删除没有用处的代码时,显示警告
          keep_fargs: true,  // 默认true。阻止压缩器干掉那些没有用到的函数参数。你需要它来保护某些依赖
          sequences: true, // (默认true) -- 连续声明变量,用逗号隔开来。可以设置为正整数来指定连续声明的最大长度。如果设为true 表示默认200个,设为false或0则禁用。 sequences至少要是2,1的话等同于true(即200)。默认的sequences设置有极小几率会导致压缩很慢,所以推荐设置成20或以下。
          dead_code: true,  //  移除没被引用的代码
          conditionals: true, // 优化if等判断以及条件选择
          booleans: true, // 优化布尔运算,例如 !!a? b : c → a ? b : c
          unused: true, // 干掉没有被引用的函数和变量。(除非设置"keep_assign",否则变量的简单直接赋值也不算被引用。)
          if_return: true, //  优化 if/return 和 if/continue
          join_vars: true, // 合并连续 var 声明
          drop_console: true, // 剔除代码中的console.*
          drop_debugger: true, // 剔除代码中的 debugger
        }
      }
    }),
    // webpack 会自动将出口js文件加入到这个html文件中。
    new HtmlWebpackPlugin({template: './src/index.html'}),
    new ExtractTextPlugin('[name].css'),
    // 提取公共代码块
    new webpack.optimize.CommonsChunkPlugin({
      name: ['vendor', 'manifest'],
     }),
  ],
  // 这样写 会在浏览器的  sources 栏中加载源代码,方便调试
  devtool: "cheap-source-map",
  devServer: {
    contentBase: path.join(__dirname, 'build/dist'),
    compress: true,
    port: 9000,
    // 这个配置不好用,会报:[HMR] Hot Module Replacement is disabled.
    // 可以在 package.json  中用 :webpack-dev-server --hot --inline 来代替
    // hot: true,
  },
  // 文件过大时 给出警告
  /* performance: {
    maxEntrypointSize: 102400,
    maxAssetSize: 20480,
    hints: "warning",
  } */
};
module.exports = config;

五、UglifyJsPlugin

请参照:UglifyJS中文文档

上一篇下一篇

猜你喜欢

热点阅读