在弄清楚如何完全创建和设置我想发布以在浏览器环境中使用的 npm 包时遇到一些问题。
我想我遗漏了一些关于如何生成索引文件的信息。
我通过两个项目目录中的 npm link
将 testpackage
链接到我的测试应用程序。我的测试应用程序是用 webpack 和 babel 设置的,是用 es6 编写的,所以使用 import
和 export
。
源代码是用 es6 编写的,并通过 babel 转译。以下是带有构建命令的 package.json
的相关部分:
{
"name": "testpackage",
"main": "index.js",
"scripts": {
"build": "babel src --out-dir dist",
"lint": "eslint ."
},
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"
}
}
我试过以两种方式创建 index.js
文件,首先是通过 es6,然后是 module.exports
,但都不起作用。
// es6 index.js in testpackage
import store from './dist/store';
import attach from './dist/attach';
export {store, attach};
--
// index.js with modules.exports
const path = require('path');
module.exports = {
store: require(path.resolve(__dirname, './dist/store')),
attach: require(path.resolve(__dirname, './dist/attach'))
}
在这个 es6 第一个案例中,我正在导入 testpackage
的测试应用程序没有找到 dist
。
未找到模块:错误:无法解析“/usr/local/apps/testpackage”中的“dist/store”
在第二种情况下,代码显然是要通过节点运行,而是直接加载到浏览器中。我在想测试应用程序中的 webpack + babel 转译步骤应该运行这个,但它不是。
我缺少这个设置吗?
最佳答案
终于明白了。第一种方法是正确的。我需要在导入和导出其他文件的 src 目录中创建一个 es6 index.js。然后babel将其转译到/dist目录下,package.json中的main
指向/dist/index。问题是我没有转换索引。
关于javascript - index.js for npm package for browser transpiled with babel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978746/