【问题标题】:What happened to module filenames after minification缩小后模块文件名发生了什么
【发布时间】:2019-10-22 14:05:06
【问题描述】:

我正在尝试解决this code 的问题:

    import globalComponents from './global-components';
    // ...
    globalComponents.forEach((component) => {
      // eslint-disable-next-line no-underscore-dangle
      Vue.component(component.__file.split('/').pop().split('.')[0], component);
    });

globalComponents 是一个包含 index.js 的目录,它导入和重新导出两个 Vue.js 组件文件。我不知道你能做到这一点,但我想这是一种类似 python 模块层次结构的方法。

无论如何,这段代码在调试模式下运行良好,但在为发布而构建时,应用程序无法加载,因为组件对象没有 __file 属性。这段代码在做什么?如何让它在生产版本中工作?

【问题讨论】:

    标签: javascript vue.js webpack module node-modules


    【解决方案1】:

    由于您使用的是webpack,因此使用require.context() 可能更容易,这样可以省去一些麻烦。

    const files = require.context('./global-components', true, /\.vue$/i);
    files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
    

    通过这种方式,您不需要维护一个仅为此目的导入和导出所有组件的index.js 文件。只需在该目录中创建 SFC 即可。

    【讨论】:

    • 谢谢。这似乎确实有效,并且不必在 index.js 中包含样板代码很棒!
    • 你能解释一下为什么其他方法不起作用吗?为什么require.context 保留文件名而导入不保留?
    • @RalphGiles 当然,你可以看到it right here。我想我的方法为什么有效......因为当您使用正则表达式或 glob 模式时,webpack 会为您创建一个特殊的上下文。你的方式依赖于vue-loader
    • 知道了。再次感谢!
    猜你喜欢
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多