如何通过Webpack(vue-cli)在生产构建中排除CommonJS类库?
Alright, let's get to the bottom of why your vue-class-component and vue-property-decorator externals setup isn't working. The core problem is actually the CDN files you're loading, not the Webpack config syntax you tried. Here's how to fix it properly:
1. Fix the CDN Links to Load UMD Modules
You noticed the file suffixes differ, but you didn't realize that the default CDN link for vue-class-component points to a CommonJS module (.common.js), which can't run directly in browsers—it won't expose the global VueClassComponent variable Webpack is looking for.
Update your index.html to load the UMD version of vue-class-component explicitly:
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <!-- Load the UMD build of vue-class-component, not the CommonJS one --> <script src="https://cdn.jsdelivr.net/npm/vue-class-component@7.2.5/dist/vue-class-component.umd.js"></script> <!-- vue-property-decorator's default CDN link already points to its UMD build, so no change needed --> <script src="https://cdn.jsdelivr.net/npm/vue-property-decorator@9.0.0"></script>
2. Simplify the Externals Configuration
You don't need the commonjs2 or umd prefixes in your externals—those are for Node.js module resolution, but we're working with browser globals here. Use a clean mapping of package names to their global variable names:
// vue.config.js module.exports = { configureWebpack: { externals: { vue: 'Vue', 'vue-class-component': 'VueClassComponent', 'vue-property-decorator': 'VuePropertyDecorator' } } }
3. Verify the Fix
- Run your build command (e.g.,
npm run build) and check the bundle size—it should drop significantly since those two libraries are no longer included. - Fire up your app and confirm components using
@Componentor other decorators work as expected.
Why This Works
- UMD modules are designed to run in both browsers and Node.js, so they'll expose the correct global variables (
VueClassComponentandVuePropertyDecorator) to the window object. - Webpack's externals config tells it: "When I import 'vue-class-component', don't bundle it—use the global
VueClassComponentvariable instead."
Your TypeScript imports (import { Component } from 'vue-property-decorator') will work seamlessly with this setup, since Webpack maps the import to the global VuePropertyDecorator.Component under the hood.
内容的提问来源于stack exchange,提问作者hgb123

