Webpack+TypeScript如何保留外部库import语句至运行时?
解决Webpack无法解析Wix-Velo库并保留import语句的问题
我在基于Wix-Velo开发时,会导入这类Wix官方库:
import * as whf from 'wix-http-functions';
已经创建了对应的.d.ts文件让VSCode能正常识别类型,但Webpack打包时会报错无法解析wix-http-functions。我需要让Webpack跳过这个库的打包,直接保留原import语句,因为这些库是Wix运行环境提供的外部依赖。
我的当前webpack.config.js配置如下:
const path = require('path'); module.exports = { entry: { calendar: './ts/calendar.ts', poster: './ts/html/poster.ts', mailchimp: './ts/mailchimp.ts', tcb: './ts/wix/tcb.ts', zaikoInject: './ts/zaiko-inject.ts', }, devtool: 'inline-source-map', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', include: path.resolve(__dirname, "ts"), }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { library: { name: '[name]', type: 'var', }, filename: '[name].js', path: path.resolve(__dirname, 'dist'), }, "optimization": { "minimize": false, usedExports: true, }, mode: "development", };
解决方案
核心是使用Webpack的externals配置,告诉Webpack哪些模块属于外部环境提供,不需要打包进bundle,直接保留原导入语句。
配置方式
在webpack.config.js的module.exports对象中添加externals字段,有两种配置方式可选:
- 单个指定Wix库
如果只需要排除特定的Wix库,比如wix-http-functions:
externals: { 'wix-http-functions': 'commonjs wix-http-functions' }
- 批量排除所有Wix官方库
如果要排除所有以wix-开头的库(比如wix-data、wix-users等),可以用正则匹配:
externals: [ /^wix-.+/ ]
修改后的完整配置
const path = require('path'); module.exports = { entry: { calendar: './ts/calendar.ts', poster: './ts/html/poster.ts', mailchimp: './ts/mailchimp.ts', tcb: './ts/wix/tcb.ts', zaikoInject: './ts/zaiko-inject.ts', }, devtool: 'inline-source-map', // 添加externals配置 externals: [ /^wix-.+/ ], module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', include: path.resolve(__dirname, "ts"), }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { library: { name: '[name]', type: 'var', }, filename: '[name].js', path: path.resolve(__dirname, 'dist'), }, "optimization": { "minimize": false, usedExports: true, }, mode: "development", };
原理说明
externals是Webpack的核心配置之一:
- Webpack会跳过对这些模块的解析和打包,完全保留原
import语句 - 运行时,这些模块由Wix的运行环境直接提供,不需要bundle包含它们
- 已有的TypeScript类型定义文件(
.d.ts)已经保证了VSCode的类型提示正常,无需额外修改ts-loader配置
内容的提问来源于stack exchange,提问作者Fergal Daly
相关产品推荐
相关产品推荐

