Babel 7.7-用core-js @ 3替换babel / polyfill

时间:2019-11-24 09:56:45

标签: javascript babeljs webpack-4 babel-polyfill

由于@ babel / polyfill在7.4.0中已弃用,因此我试图直接添加core-js并通过corejs选项as decribed in the Babel documentation.设置版本。

但是,尝试这种方法时,我遇到了与polyfill相关的错误。 「(°ヘ°)

该应用可以编译,但是从不渲染-控制台记录错误"can't access lexical declaration `MEDIA_LARGE' before initialization"

我的webpack.config.js(Webpack 4.41.2)

'use strict'
const path = require('path')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const TerserPlugin = require('terser-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

process.env.NODE_ENV = process.env.NODE_ENV || 'development'
if (process.env.NODE_ENV === 'test') {
  require('dotenv').config({ path: '.env.test' })
} else if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({ path: '.env.development' })
} else if (process.env.NODE_ENV === 'production') {
  require('dotenv').config({ path: '.env.production' })
} else {
  require('dotenv').config({ path: '.env.development' })
}

module.exports = (env) => {
  const isDev = env === 'development'
  const bundleName = 'bundle.js'

  const firebasePlugin = new webpack.DefinePlugin({
    'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
    'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
    'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
    'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
    'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
    'process.env.FIREBASE_MESSAGING_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGING_SENDER_ID),
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  })

  const cssExtractPlugin = new MiniCssExtractPlugin({
    filename: '[name].css',
    chunkFilename: '[id].css',
    ignoreOrder: false
  })

  const plugins = isDev ? 
  [
    firebasePlugin,
    cssExtractPlugin,
    new BundleAnalyzerPlugin()
  ] 
  : 
  [
    firebasePlugin,
    cssExtractPlugin,
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ]

  // build WEBPACK CONFIG
  const config = {}

  config.devServer = {
    contentBase: path.join(__dirname, 'public'), //absolute path
    historyApiFallback: true,
    publicPath: '/dist'
  }

  config.mode = env
  config.watch = isDev
  config.resolve = {
    extensions: ['.js', '.jsx']
  }

  config.devtool = 'source-map'

  config.entry = ['./src/app.js']

  config.output = {
    path: path.join(__dirname, 'public', 'dist'), //absolute path
    filename: bundleName
  }

  config.optimization = {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        sourceMap: isDev,
        cache: true,
        parallel: true,
        terserOptions: {
          mangle: true,
          keep_classnames: true,
          keep_fnames: true,
          output: {
            comments: false
          }
        }
      })
    ]
  }
  config.plugins = plugins;
  config.module = {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: [
        /node_modules/,
        /firebase-functions/,
        /tests/
      ],
      use: {
        loader: 'babel-loader'
      }
    },
    {
      test: /\.svg$/,
      loader: 'svg-inline-loader'
    },
    {
      test: /\.s[ac]ss$/i,
      use: [
        'style-loader',
        'css-loader',
        'sass-loader',
      ],
    },
    {
      test: /\.css$/,
      use: [
        {
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../',
            hmr: process.env.NODE_ENV === 'development',
          },
        },
        'css-loader',
      ],
    }
    ]
  }
  return config
}

我的babel.rc(Babel 7.7.2)

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1"
        },
        "useBuiltIns": "usage",
        "corejs": "3",
        "debug": true
      }
    ],
    ["@babel/preset-react"]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    "emotion"
  ]
}

从Babel调试日志中,我可以看到正在使用polyfills

[C:\...\NotificationDateAlertList.js] Based on your code and targets, core-js polyfills were not added.

[C:\...\NotificationList.js] Added following core-js polyfill: es.array.sort { "safari":"11.1" }

[C:\...\commentActions.js] Added following core-js polyfill: es.promise { "edge":"17", "firefox":"60" }

[C:\...\CommentListItem.js] Based on your code and targets, core-js polyfills were not added.

[C:\...\CommentForm.js] Added following core-js polyfill: es.string.match { "edge":"17" }

我已经确定了问题,但无法弄清楚为什么会收到错误消息。在下面的减速器中,我从操作中导入常量MEDIA_LARGE。

reducers / route.js

import { MEDIA_LARGE } from '../actions/routeActions'
const routeDefault = {
  page: '',
  prevPath: {},
  lastListPage: '',
  lastCatId: '',
  mediaSize: 'large'
}

const routeReducer = (state = routeDefault, action) => {
  //...
}

actions / routeActions.js export const MEDIA_LARGE = 'large'

替换常量导入有效,但是我怀疑这种行为还会破坏其他文件中的其他常量导入。 :/

const routeDefault = {
  page: '',
  prevPath: {},
  lastListPage: '',
  lastCatId: '',
  mediaSize: 'large'
}

为什么这行不通?我在这里做错什么了吗?

亲切的问候/ K

0 个答案:

没有答案