【问题标题】:import css file from node_modules using require()使用 require() 从 node_modules 导入 css 文件
【发布时间】:2021-03-04 12:46:07
【问题描述】:

在 Vue 应用程序中工作 我正在尝试从 node_modules 中的几个依赖项动态导入一个 css 文件。

使用带有静态字符串的require('path') 可以正常工作并加载我的 css 文件。 一旦我尝试将函数参数传递给 require() 函数,它就不起作用了。

const getFontDeclaration = (path) => {
  {
    return new Promise((resolve) => {
       // a static string works fine
      require('@foo/own-package-name/dist/assets/css/font-face.css');

      // using an argument does not work
      require(path);

      // import(path)
      // does not work either

      // while this work fine too
      import('@foo/own-package-name/dist/assets/css/font-face.css')     
        .then(() => {
          resolve();
        })
    });
  }
};

有什么线索或方向吗?使用 import() 和 require() 有点混淆

【问题讨论】:

    标签: javascript vue.js webpack


    【解决方案1】:

    require 不能完美地动态工作,因为 webpack 不知道你的 path 参数的路径。但是,如果您在 require 中添加某种模板文字,它将起作用(例如 my-fonts/${path})。

    import 动态和惰性地导入一些东西。

    您可以在 Webpack import 函数here 中找到更多详细信息。

    【讨论】:

    • 谢谢!只有当传递给require() 的内容以字符串开头时,它才会起作用。 const reqPath = url.replace('@foo/', '')然后require('@foo' + reqPath)
    • 不客气 :) 您可以使用模板文字使其更简洁 ;)
    【解决方案2】:

    为了清楚起见

    const getFontDeclaration = (path) => {
      // using a variable directly will not work
      require(path);
    
      // removing a part of the path and prepending it with a static string will work
      const reqPath = url.replace('@foo/', '');
      require(`@foo/${reqPath}`);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 2019-11-05
      • 2017-11-17
      • 2018-10-01
      • 2019-10-21
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多