zl程序教程

您现在的位置是:首页 >  其他

当前栏目

webpack-notebook

2023-02-19 12:20:08 时间

引言

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)
npm install -D babel-loader @babel/core @babel/preset-env webpack

Install it as development dependency.

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").

npm install --save @babel/runtime

webpack.config.js

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

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry"
      }
    ]
  ]
}

Q&A

补充

BREAKING CHANGE:

参考:

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

resolve: {
  alias: {
    '@': path.resolve(__dirname, './src')
  },
  extensions: ['*', '.js', '.json'],
  fallback: { 
    "util": false,
    "path": false,

  }
},

参考

感谢帮助!