webpack5打包js+jquery项目

项目需要兼容ie8,采用纯js+jquery,并且使用es5的语法

项目结构:一个构造函数(class)放一个文件,入口文件放inde.js

注意:ie8,jquery只能使用1.X的版本,最终使用1.12.4; 不用promise 等,全部用回调

为提高性能 使用webpack,将多个js文件打包成一个

文件引用导出 使用es6的import export  因为webpack可以处理import export

import {Util} from './util.js';
export function Util() { }


import Util from './util.js';
export default function Util() { }

 

 webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  mode: 'production',
  entry: {
    'index': ['./src/index.js','./src/util.js'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      minify: false,
    }),
    new MiniCssExtractPlugin({
      filename: "[name]_[contenthash:8].css"
    }),
    new webpack.ProvidePlugin({
      $: 'jquery', 
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  optimization: {
    minimizer: [
      `...`,
      new CssMinimizerPlugin(),
    ],
  },
  output: {
    filename: '[name]_[contenthash:8].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true, 
  },
  target: ['web','es5'], // 解决打包后还有箭头函数的问题
};

 

webpack中文件打包 hash、chunkhash、contenthash 的区别

引入jquery的方法

1直接引入

import $ from './jquery-1.12.4.min.js'
window.$ = $
window.jQuery = $

import $ from 'jquery'

package.json

 "dependencies": {
    "jquery": "1.12.4"
  },

 

3 使用 webpack.ProvidePlugin

package.json

 "dependencies": {
    "jquery": "1.12.4"
  },

 


const webpack = require('webpack'); // 不能用{webpack} 会报错
 
new webpack.ProvidePlugin({
      $: 'jquery', 
    })
 

 

 

坑:ie8  Object.defineProperty  

解决: 在HTML页面添加以下代码

<script>
  // ie8兼容
  var origDefineProperty = Object.defineProperty;
  var arePropertyDescriptorsSupported = function () {
    var obj = {};
    try {
      origDefineProperty(obj, "x", {enumerable: false, value: obj});
      for (var _ in obj) {
        return false;
      }
      return obj.x === obj;
    } catch (e) {
      /* this is IE 8. */
      return false;
    }
  };
  var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  if (!supportsDescriptors) {
    Object.defineProperty = function (a, b, c) {
      //IE8支持修改元素节点的属性
      if (origDefineProperty && a.nodeType == 1) {
        return origDefineProperty(a, b, c);
      } else {
        a[b] = c.value || (c.get && c.get());
      }
    };
  }
</script>

 

加上jquery.js文件一起打包,,ie8还是不行,sad!!!不打包还行ie8还可以打开,打包后就不行了,啊啊啊

最后方案: jquery.js,单独加载,其他打包成一个js文件

ps:或许可以把项目中的jq代码去掉,参考这个https://youmightnotneedjquery.com/

 

jquery需要先加载,再加载index.js

new HtmlWebpackPlugin({
      template: './index.html',
      minify: false,
      inject: false, // 不插入, 使用自定义模板
    }),
<link href="<%=htmlWebpackPlugin.files.css[0] %>" rel="stylesheet">
<script type="text/javascript" src="<%=htmlWebpackPlugin.files.js[0]%>">
参考
html-webpack-plugin详解
index.html如下
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <title>自定义模板</title>
  <link href="<%=htmlWebpackPlugin.files.css[0] %>" rel="stylesheet">
  <script>
    window.onerror = function (message, url, line) {
      alert("Message : " + message + "\nURL : " + url + "\nLine Number : " + line);
      // Return true to supress the browser error messages (like in older versions of Internet Explorer)
      return true;
    }
</head>

<body>

</body>

<script>
  // ie8兼容
  var origDefineProperty = Object.defineProperty;
  var arePropertyDescriptorsSupported = function () {
    var obj = {};
    try {
      origDefineProperty(obj, "x", {enumerable: false, value: obj});
      for (var _ in obj) {
        return false;
      }
      return obj.x === obj;
    } catch (e) {
      /* this is IE 8. */
      return false;
    }
  };
  var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  if (!supportsDescriptors) {
    Object.defineProperty = function (a, b, c) {
      //IE8支持修改元素节点的属性
      if (origDefineProperty && a.nodeType == 1) {
        return origDefineProperty(a, b, c);
      } else {
        a[b] = c.value || (c.get && c.get());
      }
    };
  }
</script>

<script>
    function loadScript(url, callback) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      if (script.readyState) {
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" || script.readyState == "complete") {
            script.onreadystatechange = null;
            if (callback) {
              callback();
            }
          }
        }
      } else {
        script.onload = function () {
          if (callback) {
            callback();
          }
        }
      }
      script.src = url;
      document.getElementsByTagName('head')[0].appendChild(script);
    }


    loadScript('/assets/plugins/jquery/jquery-1.12.4.min.js', function () {
      loadScript("<%=htmlWebpackPlugin.files.js[0] %>");  
    });
  </script> 
</html>

 

posted @ 2021-12-09 15:59  litiyi  阅读(2095)  评论(0编辑  收藏  举报