webpack-notebook

2023-01-02 11:18:18 浏览数 (1)

引言

Polyfill是什么

Polyfill 是一块代码(通常是 Web 上的 JavaScript),用来为旧浏览器提供它没有原生支持的较新的功能。

比如说 polyfill 可以让 IE7 使用 Silverlight 插件来模拟 HTML Canvas 元素的功能,或模拟 CSS 实现 rem 单位的支持,或text-shadow,或其他任何你想要的功能。(引用自MDN)

Webpack 5 babel

参考:

  • webpack
  • [@babel/plugin-transform-runtime · Babel](https://babel.dev/docs/en/babel-plugin-transform-runtime)
  • [@babel/preset-env · Babel](https://babel.dev/docs/en/babel-preset-env)
代码语言:javascript复制
npm install -D babel-loader @babel/core @babel/preset-env webpack

Install it as development dependency.

代码语言:javascript复制
npm install --save-dev @babel/preset-env
npm install --save-dev @babel/plugin-transform-runtime

and @babel/runtime as a production dependency (since it's for the "runtime").

代码语言:javascript复制
npm install --save @babel/runtime

webpack.config.js

代码语言:javascript复制
module: {
  rules: [
    {
      test: /.m?js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
          plugins: ['@babel/plugin-transform-runtime']
        }
      }
    }
  ]
}

.babelrc

代码语言:javascript复制
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry"
      }
    ]
  ]
}

Q&A

补充

BREAKING CHANGE:

参考:

  • node.js - Webpack 5 Errors - Cannot Resolve 'crypto', 'http', and 'https' in ReactJS Project - Stack Overflow
  • vue中webpack5版本报错If you want to include a polyfill you need , If you don‘t want to include a polyfill_u011608672的博客-CSDN博客
代码语言:javascript复制
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }
 @ ./node_modules/webpack/lib/index.js 539:10-38
 @ ./src/js/utils.js 1:0-31
 @ ./src/js/plugincore.js 3:0-31 56:22-43 95:21-41 147:19-33 154:23-39 230:15-20
 @ ./src/main.js 2:0-44 7:15-25

webpack.config.js

代码语言:javascript复制
resolve: {
  alias: {
    '@': path.resolve(__dirname, './src')
  },
  extensions: ['*', '.js', '.json'],
  fallback: { 
    "util": false,
    "path": false,

  }
},

参考

感谢帮助!

0 人点赞