首页 > 解决方案 > 如何使用 babel 正确编译 react 模块,以及如何正确处理导入

问题描述

我认为我在转译的 index.js 文件中重新声明导入时遇到问题

我正在将一些 react es6 组件转换为单个 index.js 文件。然后通过运行“npm install /path/to/myComponents”将这些组件导入到另一个项目中

当我将这些组件导入我的主项目时,我得到了错误

SyntaxError: Identifier '_interopRequireDefault' has already been declared
...
> 53 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
...

这一行确实在我的 index.js 中多次出现在一段看起来像这样的代码中

var _react = _interopRequireDefault(require("react"));

var _componentX = require("./ComponentX.js");

var _propTypes = _interopRequireDefault(require("prop-types"));

var _this = void 0;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var ComponentY = function ComponentY(props) {

我想修复我如何转译代码,这样就不会发生这种情况,或者我只是忽略重新声明,无论如何它们都是一样的。

我的 src 文件夹(我的 react 组件所在的位置)包含一个 index.js 文件和一个 components 文件夹,其中包含 3 个组件。这些组件中的每一个都包含

import React from 'react';
import propTypes from 'prop-types'

其中两个导入第三个组件


可能的解决方案

我很确定解决方案涉及更改“构建”行的某些内容:"./node_modules/.bin/babel src --out-file index.js".但我不知道该怎么做。

这些是我的组件文件夹中的文件,而不是我的主项目文件夹(导入组件文件夹。)


.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]
}

包.json

{
    "name": "myComponent",
    "version": "1.0.0",
    "scripts": {
        "build": "./node_modules/.bin/babel src --out-file index.js"
    },
    "dependencies": {},
    "peerDependencies": {
        "react": "^16.6.1",
        "react-dom": "^16.6.3"
    },
    "devDependencies": {
        "@babel/cli": "^7.5.5",
        "@babel/core": "^7.5.5",
        "@babel/plugin-proposal-class-properties": "^7.5.5",
        "@babel/preset-env": "^7.5.5",
        "@babel/preset-react": "^7.0.0",
        "react": "^16.8.6",
        "react-dom": "^16.8.6"
    }
}

webpack.config.js

var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2' // THIS IS THE MOST IMPORTANT LINE! :mindblow: I wasted more than 2 days until realize this was the line most important in all this guide.
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  externals: {
    'react': 'commonjs react' // this line is just to use the React dependency of our parent-testing-project instead of using our own React.
  }
};

标签: javascriptreactjswebpackbabeljs

解决方案


推荐阅读