React Development和Build版本在IE 11和Edge中不起作用-Webpack/Babel [英] React Development and Build version not working in IE 11 and Edge - Webpack/Babel

查看:266
本文介绍了React Development和Build版本在IE 11和Edge中不起作用-Webpack/Babel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发和构建版本在IE 11和Edge中不起作用.这是我的webpack配置和程序包json文件.

Development and build version not working in IE 11 and Edge. Here are my webpack config and package json file.

我已使用以下回购协议. https://github.com/kriasoft/react-starter-kit

I have used below repo. https://github.com/kriasoft/react-starter-kit

我一直在尝试使用各种babel软件包和webpack配置来解决此问题.

I have been trying to fix this issue using various babel packages and webpack configurations.

箭头功能似乎无法正常工作.

Arrow function seems not to be working.

这是错误.

webpack.config.js

/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import WebpackAssetsManifest from 'webpack-assets-manifest';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import overrideRules from './lib/overrideRules';
import pkg from '../package.json';

const ROOT_DIR = path.resolve(__dirname, '..');
const resolvePath = (...args) => path.resolve(ROOT_DIR, ...args);
const SRC_DIR = resolvePath('src');
const BUILD_DIR = resolvePath('build');

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
  process.argv.includes('--analyze') || process.argv.includes('--analyse');

const reScript = /\.(js|jsx|mjs)$/;
const reStyle = /\.(css|less|styl|sass|sss|scss)$/;
const reImage = /\.(bmp|gif|jpg|jpeg|png|svg)$/;
const staticAssetName = isDebug
  ? '[path][name].[ext]?[hash:8]'
  : '[hash:8].[ext]';

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------
console.log('isDebug', isDebug)
const config = {
  context: ROOT_DIR,

  mode: isDebug ? 'development' : 'production',

  output: {
    path: resolvePath(BUILD_DIR, 'public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug
      ? '[name].chunk.js'
      : '[name].[chunkhash:8].chunk.js',
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: [SRC_DIR, resolvePath('tools')],
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          configFile: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: pkg.browserslist,
                },
                forceAllTransforms: !isDebug, // for UglifyJS
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-flow
            '@babel/preset-flow',
            // JSX
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            ['@babel/preset-react', { development: isDebug }]
          ],
          plugins: [
            'relay',
            // Experimental ECMAScript proposals
            '@babel/plugin-proposal-class-properties',
            '@babel/plugin-syntax-dynamic-import',
            // Treat React JSX elements as value types and hoist them to the highest scope
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
            ...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
            // Replaces the React.createElement function with one that is more optimized for production
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
            ...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
            // Remove unnecessary React propTypes from the production build
            // https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
            ...(isDebug ? [] : ['transform-react-remove-prop-types']),
          ],
        },
      },
      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: SRC_DIR,
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: SRC_DIR,
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: {
                localIdentName: isDebug
                  ? '[name]-[local]-[hash:base64:5]'
                  : '[hash:base64:5]',
              },
            },
          },

          // Apply PostCSS plugins including autoprefixer
          {
            loader: 'postcss-loader',
            options: {
              config: {
                path: './tools/postcss.config.js',
              },
            },
          },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.(scss|sass)$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: resolvePath(
                'node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['@babel/polyfill', './src/client.js'],
  },

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/webdeveric/webpack-assets-manifest#options
    new WebpackAssetsManifest({
      output: `${BUILD_DIR}/asset-manifest.json`,
      publicPath: true,
      writeToDisk: true,
      customize: ({ key, value }) => {
        // You can prevent adding items to the manifest by returning false.
        if (key.toLowerCase().endsWith('.map')) return false;
        return { key, value };
      },
      done: (manifest, stats) => {
        // Write chunk-manifest.json.json
        const chunkFileName = `${BUILD_DIR}/chunk-manifest.json`;
        try {
          const fileFilter = file => !file.endsWith('.map');
          const addPath = file => manifest.getPublicPath(file);
          const chunkFiles = stats.compilation.chunkGroups.reduce((acc, c) => {
            acc[c.name] = [
              ...(acc[c.name] || []),
              ...c.chunks.reduce(
                (files, cc) => [
                  ...files,
                  ...cc.files.filter(fileFilter).map(addPath),
                ],
                [],
              ),
            ];
            return acc;
          }, Object.create(null));
          fs.writeFileSync(chunkFileName, JSON.stringify(chunkFiles, null, 2));
        } catch (err) {
          console.error(`ERROR: Cannot write ${chunkFileName}: `, err);
          if (!isDebug) process.exit(1);
        }
      },
    }),

    ...(isDebug
      ? []
      : [
          // Webpack Bundle Analyzer
          // https://github.com/th0r/webpack-bundle-analyzer
          ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
        ]),
  ],

  // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        },
      },
    },
  },

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['@babel/polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: BUILD_DIR,
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(preset =>
              preset[0] !== '@babel/preset-env'
                ? preset
                : [
                    '@babel/preset-env',
                    {
                      targets: {
                        node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                      },
                      modules: false,
                      useBuiltIns: false,
                      debug: false,
                    },
                  ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            emitFile: false,
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './chunk-manifest.json',
    './asset-manifest.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

export default [clientConfig, serverConfig];


package.json

{
  "name": "web",
  "version": "0.0.0",
  "private": true,
  "engines": {
    "node": ">=8.16.2",
    "npm": ">=6.4.1"
  },
  "browserslist": [
    ">1%",
    "ie 11"
  ],
  "dependencies": {
    "@babel/polyfill": "^7.7.0",
    "@date-io/moment": "^1.3.11",
    "@material-ui/core": "^4.7.0",
    "@material-ui/icons": "^4.5.1",
    "@material-ui/lab": "^4.0.0-alpha.33",
    "@material-ui/pickers": "^3.2.8",
    "@material-ui/styles": "^4.6.0",
    "aws-sdk": "^2.580.0",
    "axios": "^0.19.0",
    "babel-plugin-relay": "^7.1.0",
    "body-parser": "^1.19.0",
    "classnames": "^2.2.6",
    "clsx": "^1.0.4",
    "cookie-parser": "^1.4.3",
    "dotenv": "^8.2.0",
    "express": "^4.16.3",
    "express-graphql": "~0.8.0",
    "express-jwt": "^5.3.1",
    "express-session": "^1.17.0",
    "fs": "0.0.1-security",
    "graphql": "^14.5.8",
    "history": "^4.10.1",
    "isomorphic-style-loader": "^5.1.0",
    "jsonwebtoken": "^8.3.0",
    "material-ui-color-picker": "^3.2.0",
    "node-fetch": "^2.2.0",
    "normalize.css": "^8.0.1",
    "passport": "^0.4.0",
    "passport-facebook": "^3.0.0",
    "passport-local": "^1.0.0",
    "pg": "^7.14.0",
    "pretty-error": "^2.1.1",
    "prismjs": "^1.17.1",
    "prop-types": "^15.6.2",
    "query-string": "^6.9.0",
    "react": "^16.12.0",
    "react-cookie": "^4.0.1",
    "react-dom": "^16.12.0",
    "react-helmet": "^5.2.1",
    "react-material-ui-form-validator": "^2.0.9",
    "react-page-loading": "^1.0.2",
    "react-perfect-scrollbar": "^1.5.3",
    "react-relay": "^7.1.0",
    "react-router-dom": "^5.1.2",
    "reconnecting-websocket": "^4.2.0",
    "relay-runtime": "^7.1.0",
    "sequelize": "^5.21.2",
    "serialize-javascript": "^2.1.0",
    "source-map-support": "^0.5.9",
    "sqlite3": "^4.0.8",
    "striptags": "^3.1.1",
    "subscriptions-transport-ws": "^0.9.16",
    "universal-router": "^8.3.0",
    "validate.js": "^0.13.1",
    "whatwg-fetch": "^3.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/node": "^7.7.0",
    "@babel/plugin-proposal-class-properties": "^7.7.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-transform-react-constant-elements": "^7.0.0",
    "@babel/plugin-transform-react-inline-elements": "^7.0.0",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-flow": "^7.0.0",
    "@babel/preset-react": "^7.7.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.0.3",
    "babel-jest": "^24.9.0",
    "babel-loader": "^8.0.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.18",
    "browser-sync": "^2.24.7",
    "chokidar": "^3.3.0",
    "css-loader": "^3.2.0",
    "cssnano": "^4.1.10",
    "enzyme": "^3.6.0",
    "eslint": "^5.6.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-prettier": "^6.6.0",
    "eslint-import-resolver-node": "^0.3.2",
    "eslint-loader": "^3.0.2",
    "eslint-plugin-css-modules": "^2.9.1",
    "eslint-plugin-flowtype": "^3.13.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jest": "^23.0.4",
    "eslint-plugin-jsx-a11y": "^6.1.1",
    "eslint-plugin-prettier": "^3.1.1",
    "eslint-plugin-react": "^7.11.1",
    "execa": "^3.3.0",
    "file-loader": "^4.2.0",
    "flow-bin": "^0.112.0",
    "front-matter": "^3.0.2",
    "glob": "^7.1.6",
    "husky": "^3.0.9",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^24.9.0",
    "lint-staged": "^9.4.3",
    "log-symbols": "^3.0.0",
    "markdown-it": "^10.0.0",
    "mkdirp": "^0.5.1",
    "node-sass": "^4.13.0",
    "null-loader": "^3.0.0",
    "opn-cli": "^5.0.0",
    "pixrem": "^5.0.0",
    "pleeease-filters": "^4.0.0",
    "postcss": "^7.0.2",
    "postcss-calc": "^7.0.1",
    "postcss-flexbugs-fixes": "^4.1.0",
    "postcss-import": "^12.0.0",
    "postcss-loader": "^3.0.0",
    "postcss-preset-env": "^6.6.0",
    "postcss-pseudoelements": "^5.0.0",
    "prettier": "^1.19.1",
    "puppeteer": "^2.0.0",
    "raw-loader": "^3.1.0",
    "react-deep-force-update": "^2.1.3",
    "react-dev-utils": "^9.1.0",
    "react-error-overlay": "^6.0.3",
    "react-test-renderer": "^16.12.0",
    "relay-compiler": "^7.1.0",
    "relay-config": "^7.1.0",
    "rimraf": "^3.0.0",
    "sass-loader": "^8.0.0",
    "stylelint": "^12.0.0",
    "stylelint-config-standard": "^19.0.0",
    "stylelint-order": "^3.1.1",
    "svg-url-loader": "^3.0.2",
    "terminate": "^2.1.2",
    "url-loader": "^2.2.0",
    "wait-on": "^3.3.0",
    "webpack": "^4.19.1",
    "webpack-assets-manifest": "^3.0.2",
    "webpack-bundle-analyzer": "^3.3.2",
    "webpack-dev-middleware": "^3.3.0",
    "webpack-hot-middleware": "^2.24.2",
    "webpack-node-externals": "^1.7.2"
  },
  "lint-staged": {
    "*.{js,jsx}": [
      "eslint --no-ignore --fix",
      "git add --force"
    ],
    "*.{json,md,graphql}": [
      "prettier --write",
      "git add --force"
    ],
    "*.{css,less,styl,scss,sass,sss}": [
      "stylelint --fix",
      "git add --force"
    ]
  },
  "scripts": {
    "lint-js": "eslint --ignore-path .gitignore --ignore-pattern \"!**/.*\" .",
    "lint-css": "stylelint \"src/**/*.{css,less,styl,scss,sass,sss}\"",
    "lint": "yarn run lint-js && yarn run lint-css",
    "fix-js": "yarn run lint-js --fix",
    "fix-css": "yarn run lint-css --fix",
    "fix": "yarn run fix-js && yarn run fix-css",
    "flow": "flow",
    "flow:check": "flow check",
    "test": "jest",
    "test-watch": "yarn run test --watch --notify",
    "test-cover": "yarn run test --coverage",
    "coverage": "yarn run test-cover && opn coverage/lcov-report/index.html",
    "clean": "babel-node tools/run clean",
    "copy": "babel-node tools/run copy",
    "bundle": "babel-node tools/run bundle",
    "build": "babel-node tools/run build",
    "build-stats": "yarn run build --release --analyse",
    "deploy": "babel-node tools/run deploy",
    "render": "babel-node tools/run render",
    "serve": "babel-node tools/run runServer",
    "start": "babel-node tools/run start relay",
    "relay": "relay-compiler --src ./src --schema ./schema.graphql"
  }
}

推荐答案

它与查询字符串包有关.

It was related to query-string package.

问题已解决.

引用: https://stackoverflow.com/a/49985749/7398574

这篇关于React Development和Build版本在IE 11和Edge中不起作用-Webpack/Babel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆