在过去的几天里,我一直在努力让它正常工作。
我在两个不同的js文件中有两个类:
文件 SRC/A.js:
export default class A {}
文件 SRC/B.js:
export default class B {}
我有以下入口点文件:
文件 src/index.js:
import A from './a.js'
import B from './b.js'
export { A, B }
// I don't know what else should go in here
我使用这个 webpack 配置构建它:
文件 webpack.config.js:
module.exports = {
input: 'src/index.js',
output: {
path: 'dist/',
filename: 'my-lib.js',
libraryTarget: 'commonjs-module',
}
}
并使用 webpack 命令构建它。
另一件需要注意的事情是package.json:
文件包.json:
{
"name": "my-library",
"module": "dist/my-lib.js",
"main": "dist/my-lib.js"
}
目标是将我的节点模块导入另一个项目中,然后安装它:
$ npm install --save my-module
并像这样使用它:
import {A,B} from 'my-module'
const a = new A()
const b = new B()
如何创建这样的索引.js文件,以及我的 webpack.config.js 文件应该如何才能做到这一点?
从外观上看,您有两个项目。在项目 1 中,您将创建一个库。
有关创建库的信息,请参阅 https://webpack.js.org/guides/author-libraries/
但基本上你需要导出这些类以供其他项目使用
import A from './a.js'
import B from './b.js'
module.exports = {
A,
B
}
然后在第二个项目中,您可以导入这些模块
import {A,B} from 'my-module'