为共享库包单独创建一个dist文件夹,并在其中打包该包的代码并导出包。然后,在项目中使用该包时,使用dist文件夹中的包作为引用。以下是代码示例:
在共享库包的package.json中添加以下命令:
{
"scripts": {
"build": "tsc && webpack"
}
}
在项目的package.json中添加依赖项:
{
"dependencies": {
"my-common-library": "file:../my-common-library/dist/my-common-library-1.0.0.tgz"
}
}
在共享库包的根目录下创建一个webpack.config.js文件:
const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'my-common-library.js',
path: path.resolve(__dirname, 'dist'),
library: 'my-common-library',
libraryTarget: 'umd',
umdNamedDefine: true
},
mode: 'production'
};
在共享库包的根目录下创建一个tsconfig.build.json文件:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist",
"declaration": true,
"declarationDir": "./dist"
},
"exclude": ["src/**/*.test.ts", "dist"]
}
在共享库包的根目录下运行“npm run build”命令生成代码包。
现在,在项目中使用共享库包时,不要使用源代码文件,而是使用dist文件夹中的包:
import { MyModule } from 'my-common-library';
// Use MyModule
注意:如果该共享库包还有其他依赖项,则需要将这些依赖项打包到同一个dist文件夹中,并在项目中添加它们的依赖项引用。