使用导入和导出的Babel.js无法正常工作 [英] Babel.js using Import and Export not working
问题描述
我正在尝试使用导入和导出来创建模块,但是它不起作用.
I'm trying to use import and export to create modules and it's not working.
我添加了 https://cdnjs .cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js 到index.html标头,并尝试导入js文件并收到一条错误消息,提示SyntaxError:导入声明可能仅出现在模块的顶层.我可能做错了什么?
I added https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js to the index.html header and tried to import a js file and get an error message saying SyntaxError: import declarations may only appear at top level of a module. What can I possibly be doing wrong?
我知道我可以使用require.js,而是使用import和export.
I know I can use require.js but rather use import and export.
HTML
script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js"></script
JS文件
import Mymodule from './modules/mymodule';
推荐答案
Babel无法执行模块的客户端转译,或者浏览器未普遍支持它.实际上,除非您使用插件,否则Babel会将import
转换为require()
.
Babel cannot perform client-side transpiling of modules, or rather it is not universally supported by browsers. In fact, unless you use a plugin, Babel will transform import
into require()
.
如果我运行以下代码:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script defer type="text/babel" data-presets="es2015">
import Mymod from './modules/module';
Mymod();
</script>
</head>
我收到以下错误:
未捕获的ReferenceError:未定义require
Uncaught ReferenceError: require is not defined
来自 Babel文档:
在浏览器中进行编译的用例非常有限,因此,如果您在生产站点上工作,则应在服务器端预编译脚本.有关更多信息,请参见设置构建系统.
Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side. See setup build systems for more information.
大多数人选择预编译的模块打包程序,例如 Webpack 或
Most people choose a pre-compiled module bundler like Webpack or Rollup.
如果您确实要执行此客户端,请在通过
If you really want to perform this client-side, use RequireJS with Babel run via a plugin, though you may need to use AMD syntax.
Native browser support for ES6 modules is still in early stages. But to my knowledge there isn't a preset/plugin available yet for Babel to tell it not to transform import/export
statements.
这篇关于使用导入和导出的Babel.js无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!