GLK*_*GLK 6 javascript ecmascript-6 babeljs
我正在尝试转译这个简单的代码以便在浏览器中使用,但它不起作用并且无法正常Uncaught ReferenceError: require is not defined工作require('uniq')(array);
我知道浏览器(在我的例子中是 chrome )不支持 require,但我认为这就是 babel 应该做的。
我可以使用 webpack 或 browserify,但这次我尝试使用 Babel 并遇到了这个问题。
包.json
"devDependencies": {
"@babel/cli": "^7.11.5",
"@babel/core": "^7.11.5",
"@babel/preset-env": "^7.11.5"
},
"dependencies": {
"@babel/polyfill": "^7.11.5",
"uniq": "^1.0.1"
}
Run Code Online (Sandbox Code Playgroud)
索引.js
const array = [1,1,2,2,3,5]
require('uniq')(array)
document.querySelector('p').innerText = array
Run Code Online (Sandbox Code Playgroud)
使用 babel 进行转译
npx babel index.js --out-file index2.js
index2.js(由babel生成)
"use strict";
const array = [1, 1, 2, 2, 3, 5];
require('uniq')(array);
document.querySelector('p').innerText = array;
Run Code Online (Sandbox Code Playgroud)
babel.config.json
{
"presets": [
[
"@babel/env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1",
},
"useBuiltIns": "usage",
"corejs": "3.6.4",
}
]
]
}
Run Code Online (Sandbox Code Playgroud)
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Babel Example</title>
</head>
<body>
<h1>Babel Example</h1>
<p><p>
<script src="index2.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
小智 -1
看起来这里讨论了同样的问题 https://github.com/babel/gulp-babel/issues/117
您只需要添加环境预设
--presets=@babel/preset-env
https://babeljs.io/docs/en/babel-cli#using-presets
你的转译命令应该变成
npx babel index.js --out-file index2.js --presets=@babel/preset-env
| 归档时间: |
|
| 查看次数: |
16648 次 |
| 最近记录: |