Webpack打包库无法引用函数的解决方案咨询
问题描述
我是JS库开发新手,正在做这些事:
- 用TypeScript创建库
- 用Webpack5生成打包文件
- 将库发布至npm
- 在其他项目中通过npm包使用该库
已经成功生成打包文件并上传至npm,但在步骤4遇到问题:新项目里没法引用functions.ts中的函数。不过导入库时index.ts里的代码会执行,能看到日志输出。我希望index.ts只作为函数和类的引用入口,不包含逻辑,请问要怎么修改index.ts,才能让前端JS文件可以引用functions.ts这类文件中的函数和类?
项目文件夹结构
root |-dist | |-library.js | |-src | |-functions.ts | |-index.ts | |-node_modules
functions.ts
export function add(x: number, y: number): number { return x + y; } export function multiply(x: number, y: number): number { return x * y; } export function subtract(x:number, y:number): number { return x - y; }
原index.ts
import * as func from './functions' var f1 = func.add(2, 5); console.log('f1 - ' + f1); var f2 = func.subtract(6, 2); console.log('f2 - ' + f2); var f3 = func.multiply(10, 2); console.log('f3 - ' + f3); export { func }
tsconfig.json
{ "compilerOptions": { "target": "es6", "lib": ["es6", "dom"], "outDir": "src", "sourceMap": true, "strict": true, "module": "ES2015", "esModuleInterop": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
webpack.config.js
const path = require('path'); module.exports = { entry: './src/index.ts', devtool: 'eval-source-map', mode: 'development', module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: path.resolve(__dirname, 'node_modules'), include: [path.resolve(__dirname, 'src')] }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'library.js', path: path.resolve(__dirname, 'dist'), library: 'library', libraryTarget: 'umd', umdNamedDefine: true }, };
新项目script.js(报错代码)
import * as lib from './node_modules/library/dist/library.js' var a = lib.library.add(2, 9); // -- error, library is not found. console.log(a);
解决方案
1. 改造index.ts为纯入口文件
删掉index.ts里的执行逻辑,改成直接导出functions.ts的所有成员,这样外部可以直接访问函数,不需要嵌套层级:
// 修改后的index.ts export * from './functions';
如果偏好保留命名空间(比如外部通过lib.func.add访问),也可以这么写,但推荐上面的直接导出方式,更符合npm包的常规使用习惯:
// 可选:保留命名空间的写法 import * as func from './functions'; export { func };
2. 新项目中的正确使用方式
重新打包发布库之后,新项目里可以这样导入使用:
方式1:ES模块按需导入(推荐)
// script.js import { add, subtract, multiply } from 'library'; console.log(add(2, 9)); // 输出11 console.log(subtract(6, 2)); // 输出4
如果用的是命名空间导出的写法,就这么用:
import { func } from 'library'; console.log(func.add(2, 9)); // 输出11
方式2:全局变量方式(HTML通过script标签引入时)
<script src="./node_modules/library/dist/library.js"></script> <script> console.log(library.add(2,9)); // 输出11 </script>
3. 可选优化:调整tsconfig配置
当前tsconfig.json的outDir设为src,会把编译后的JS文件和TS源码混在一起,建议改成单独的目录:
"outDir": "./dist",
内容的提问来源于stack exchange,提问作者ilito
相关产品推荐
相关产品推荐

