如何用Babel正确转译React模块并解决重复声明问题
The error you're seeing happens because Babel CLI is transpiling each component file individually and then concatenating them into a single index.js—each file gets its own copy of helper functions like _interopRequireDefault, leading to duplicate declarations when merged. Here are two reliable solutions to fix this:
Solution 1: Use Webpack to Bundle Your Library (Recommended)
You already have a webpack.config.js set up, which is the better approach for component libraries (it handles module scope and avoids duplicate helper functions automatically). Let's adjust your setup:
- Update your
package.jsonbuild script to use Webpack instead of Babel CLI:{ "scripts": { "build": "webpack --mode production" } } - Fix the Babel loader config in
webpack.config.jsto match your.babelrc(right now it only uses theenvpreset, missing React support):module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), exclude: /(node_modules|bower_components|build)/, use: { loader: 'babel-loader', options: { presets: ["@babel/preset-env", "@babel/preset-react"], plugins: [ ["@babel/plugin-proposal-class-properties", { "loose": true }] ] } } } ] } - Set the entry point correctly (your
webpack.config.jsalready uses./src/index.js, which is good) and update yourpackage.jsonto point to the bundled output:
Add this line topackage.jsonso your library can be imported correctly after installation:"main": "build/index.js" - Run the build:
Now install your library usingnpm run buildnpm install /path/to/myComponent—Webpack has bundled all components into a single file with shared helper functions, so no more duplicate declarations.
Solution 2: Use Babel Runtime to Extract Shared Helpers
If you prefer to keep using Babel CLI instead of Webpack, you can configure Babel to reuse helper functions instead of declaring them per file:
- Install required dependencies:
npm install --save-dev @babel/plugin-transform-runtime npm install @babel/runtime - Update your
.babelrcto include the runtime plugin:{ "presets": ["@babel/preset-env", "@babel/preset-react"], "plugins": [ ["@babel/plugin-proposal-class-properties", { "loose": true }], ["@babel/plugin-transform-runtime"] ] } - Run your original build command:
This will replace inline helper functions likenpm run build_interopRequireDefaultwith imports from@babel/runtime, so they're only declared once across your entire transpiled file.
Why This Happened
When you use babel src --out-file index.js, Babel processes each .js file in src separately, adding helper functions to each one. When it concatenates the results, you end up with multiple function _interopRequireDefault(...) declarations—JavaScript doesn't allow re-declaring the same function in the same scope, hence the syntax error.
内容的提问来源于stack exchange,提问作者Sam Germain

