我构建了一个相对较小的NPM包,每个包中包含大约5个不同的ES6类,它们看上去都非常像这样:
export default class MyClass {
// ...
}
然后,我为我的包裹设置了一个入口点,如下所示:
export { default as MyClass } from './my-class.js';
export { default as MyOtherClass } from './my-other-class.js';
然后,我通过webpack和babel运行入口点,最后以经过编译和缩小的index.js结尾
安装和导入软件包可以正常工作,但是当我从客户端代码执行以下操作时:
import { MyClass } from 'my-package';
它不仅导入“ MyClass”,还导入整个文件,包括每个类的所有依赖关系(我的某些类具有很大的依赖关系)。
当您尝试导入已捆绑的软件包的一部分时,我想到了webpack是如何工作的?所以我也将我的本地webpack配置设置为也node_modules/my-package
通过babel 运行,然后尝试:
import { MyClass } from 'my-package/src/index.js';
但是即使这样,它也会导入index.js导出的每个类。看来我想要的唯一运作方式是:
import MyClass from 'my-package/src/my-class.js';
但我宁愿:
- 能够导入转译和缩小的文件,这样我就不必告诉webpack在node_modules和
- 能够直接从我的入口点导入每个单独的类,而不必输入每个文件的路径
最佳做法是什么?其他人如何实现类似的设置?我注意到GlideJS的软件包具有ESM版本,例如,您可以仅导入所需的内容,而无需通过babel运行它。
有问题的软件包:https : //github.com/powerbuoy/sleek-ui
webpack.config.js
const path = require('path');
module.exports = {
entry: {
'sleek-ui': './src/js/sleek-ui.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'sleek-ui', // NOTE: Before adding this and libraryTarget I got errors saying "MyClass() is not a constructor" for some reason...
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
]
}
]
}
};
package.json
"name": "sleek-ui",
"version": "1.0.0",
"description": "Lightweight SASS and JS library for common UI elements",
"main": "dist/sleek-ui.js",
"sideEffects": false, // NOTE: Added this from Abhishek's article but it changed nothing for me :/
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production"
},
"repository": {
"type": "git",
"url": "git+https://github.com/powerbuoy/sleek-ui.git"
},
"author": "Andreas Lagerkvist",
"license": "GPL-2.0-or-later",
"bugs": {
"url": "https://github.com/powerbuoy/sleek-ui/issues"
},
"homepage": "https://github.com/powerbuoy/sleek-ui#readme",
"devDependencies": {
"@babel/core": "^7.8.6",
"@babel/preset-env": "^7.8.6",
"babel-loader": "^8.0.6",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"@glidejs/glide": "^3.4.1",
"normalize.css": "^8.0.1"
}
}
import { MyClass } from 'my-package/src/MyClass';
。您也可以删除src build打包以缩短文件路径。
main
在lib的package.json中添加了(入口点)属性?签入您的版本。以及如何捆绑您的lib软件包?