如何用 webpack 构建一个自定义本地 npm 包
webpack.config.js
const path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "main.js",
library: {
type: "umd",
export: "default",
},
libraryTarget: "umd", // 将你的 library 暴露为所有的模块定义下都可运行的方式。它将在 CommonJS, AMD 环境下运行,或将模块导出到 global 下的变量
},
target: "node",
};
package.json
需要注意 main 的配置:
"main": "dist/main.js"
main 的路径就是后续 import 或者 require 的文件路径
如何使用自定义包
- 安装本地包
npm i ./package-a -S - 成功引入之后,会在 package.json 下的依赖配置下出现
"card": "file:card" - module 规范使用
import a from "package-a" - commonjs 规范使用
const a = require("package-a")