【发布时间】:2020-07-27 18:43:27
【问题描述】:
我有一个要发布到 npm 的模块。我发现了一些 4 年以上的“解决方案”、使用 babel 5.x 的示例以及其他导致示例无法正常工作的问题。
理想情况下,我想使用 es6 编写代码并使用 babel 构建/转换,以便可以在脚本中使用 require() 或在模块中使用 import 导入。
现在,这是我的(示例)模块,展示了我尝试过的内容。
// index.js
export default function speak () {
console.log("Hello, World!");
}
// .babelrc
{
"comments":false,
"presets": [
["@babel/env", {"modules": "commonjs"}]
],
"plugins": [
"@babel/plugin-transform-modules-commonjs",
"add-module-exports"
]
}
// package.json
{
"name": "foo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.10.5",
"@babel/plugin-transform-modules-commonjs": "^7.10.4",
"@babel/preset-env": "^7.10.4",
"babel-plugin-add-module-exports": "^1.0.2"
}
}
最后,还有一个演示脚本 (demo.js)
// demo.js
const speak = require('./dist/index.js');
speak();
当我执行npm run build 然后node demo.js 时,它按预期工作:
Hello, World!
我也希望能够拥有一个模块(将"type":"module" 添加到package.json),然后以这种方式使用demo.js 文件:
import speak from './dist/index.js';
speak();
但是,我收到默认导出不可用的错误:
import speak from './dist/index.js';
^^^^^
SyntaxError: The requested module './dist/index.js' does not provide an export named 'default'
我并不关心答案是什么,我只想知道最佳实践是什么。我应该只导出为 ES6 吗?我应该只需要commonjs吗?有没有办法用两个可用目标进行转译?
注意:
- 节点 v14.5.0
- npm v6.14.6
- @babel/core v7.10.5
【问题讨论】:
标签: javascript node.js npm babeljs transpiler