You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Babel使*.mjs文件与*.js文件获得相同转译处理?

How to Get Babel to Transpile .mjs Files the Same as .js Files

Great question! The issue here is that Babel treats .mjs files differently by default—often assuming they're already using native ES module syntax that doesn't need transpilation for your target environments. Here's how to fix this and get consistent transpilation for both .js and .mjs files while keeping the .mjs extension:

Step 1: Update Your Babel Configuration

First, ensure Babel explicitly includes .mjs in the list of file extensions it processes, and configure @babel/preset-env to apply the same transpilation rules to all your JS files.

Example babel.config.json (Project-Wide Configuration)

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": "> 0.25%, not dead", // Adjust this to match your supported environments
        "modules": false, // Keep ES module syntax (set to "commonjs" if you need CJS output)
        "useBuiltIns": "usage", // Optional: Auto-inject polyfills based on targets
        "corejs": 3 // Required if using useBuiltIns
      }
    ]
  ],
  "extensions": [".js", ".mjs"] // Critical: Tell Babel to process .mjs files
}

Key Details:

  • The extensions array ensures Babel doesn't skip .mjs files entirely.
  • The targets setting dictates which syntax gets transpiled. If your target environments don't support native class syntax (e.g., older browsers like IE11, or Node.js versions < 12), Babel will automatically transpile the class in .mjs files just like it does for .js.
  • If you want to force class transpilation regardless of targets, add "include": ["transform-classes"] inside the @babel/preset-env config.

Step 2: Adjust Your Bundler Configuration (If Using Webpack/Rollup)

If you're using a bundler like Webpack, make sure it's set to process .mjs files with Babel:

Webpack Example (webpack.config.js)

module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|mjs)$/, // Match both .js and .mjs
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};

For Rollup, update your rollup.config.js to include .mjs in the extensions option of @rollup/plugin-babel.

Step 3: Verify Your Babel Version

Ensure you're using up-to-date versions of @babel/core, @babel/preset-env, and any related plugins. Older Babel versions had inconsistent handling of .mjs files. Run this to update:

npm install @babel/core@latest @babel/preset-env@latest babel-loader@latest --save-dev

Testing the Fix

After updating your configs, re-run your build process. Both .js and .mjs files should now have their class syntax transpiled to the same _createClass format you saw in your .js output.

内容的提问来源于stack exchange,提问作者David Mulder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:33