繁体   English   中英

转译 es6 模块以在浏览器中运行

[英]Transpiling es6 modules to run in the browser

我有一个使用 es6 模块的应用程序的简单示例,我想将它们转换为 es5(我不想在浏览器中运行模块,尽管我知道他们的支持率是 90%+ )。

我正在兜圈子,遇到同样的错误和问题。
这是我的设置以及我想要实现的目标:

//add.js
export function add(x, y) {
  return x + y;
}

//multiply.js
export function multiply(x, y) {
  return x * y;
}

然后我使用@babel/preset-env预设运行 babel 到 output 一个bundle.js文件。

// .babelrc
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "esmodules": true
        }
      }
    ]
  ]
}

output 看起来像这样:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.add = add;

function add(x, y) {
  return x + y;
}
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.multiply = multiply;

function multiply(x, y) {
  return x * y;
}

当我在浏览器中运行html文件时,控制台会记录以下错误:
bundle.js:3 Uncaught ReferenceError: exports is not defined

我的问题是这样的:
babel 输出的是什么?
它们是 commonjs 模块吗?
如何让 es6 模块在浏览器中运行?

"esmodules": true"是错误的。

当指定"esmodules": true"时,浏览器目标将被忽略并且脚本不会转译为 es5。output 取决于您的target 。现代浏览器处理本机 es6 模块,最好的方法是转译不同于旧版浏览器的现代浏览器(即 11 ) 并加载特定的脚本,例如

// low transpiled (loads only in modern browser)
<script type="module" src="/assets/scripts/main.js"></script>

// full transpiled (loads only in legacy browser) --> polyfill this bundle
<script nomodule src="/assets/scripts/main.legacy.js" defer></script> 

// https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack/settings/javascript/babel-config.js
const modern = {
  presets: [
    ["@babel/preset-env", {
      // define transpile level
      targets: {
        browsers: [
          "> 1% in EU",
          "not ie 11",
          "not dead"
        ]
      },
      useBuiltIns: "usage",
      corejs: 3,
    }]
  ],
  plugins: [
    "@babel/plugin-syntax-dynamic-import",
    "transform-eval"
  ],
  comments: false,
  cacheDirectory: path.join(CACHE_PATH, 'babel-loader')
};

const legacy = {
  presets: [
    ["@babel/preset-env", {
      // define transpile level
      targets: {
        browsers: [
          "> 1% in CH",
          "ie >= 11",
          "not dead"
        ]
      },
      useBuiltIns: "usage",
      corejs: 3,
    }]
  ],
  plugins: [
    "@babel/plugin-syntax-dynamic-import",
    "transform-eval"
  ],
  comments: false,
  cacheDirectory: path.join(CACHE_PATH, 'babel-loader')
};

请查看babel 文档以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM