【问题标题】:What does publicPath: "/static/" do in Webpack?publicPath: "/static/" 在 Webpack 中有什么作用?
【发布时间】:2020-09-07 17:29:38
【问题描述】:

我有一个 React、express、mongo、webpack 应用程序,在 webpack.config.jsoutput 对象中,有类似的东西:

  output: {
    filename: "bundle.js",
    path: __dirname + "/dist/bundle/",
    publicPath: "/static/",
  }

现在,我知道 filename 是最终的捆绑代码,path 是捆绑的位置,但 publicPath: "/static/" 呢?

publicPath 文档说-

它允许您指定应用程序中所有资产的基本路径。

例如,在开发中,我们可能有一个 assets/ 文件夹,它位于索引页面的同一级别。这很好,但如果我们想在生产环境中将所有这些静态资产托管在 CDN 上怎么办?


我不太明白。我没有 assets/ 文件夹,但我的资产位于 public/ 目录中。它里面有mediastylesheets 文件夹。

我也不明白这里发生了什么,在我的views/index.ejs 文件中。我的应用程序中没有index.html 文件,而是index.ejs 文件。看起来对吗?好吧,该应用程序似乎可以运行,但我似乎无法理解。

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel='stylesheet' href='/static/bundle.css' />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">
    <script src="https://kit.fontawesome.com/afb88cf987.js" crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="/static/bundle.js"></script>
  </body>
</html>

请帮帮我。多年来我一直坚持这一点。

【问题讨论】:

    标签: javascript webpack ejs


    【解决方案1】:

    publicPath 指的是你的资产包从你的index.html 所在的状态开始的位置,因此 webpack 可以为你设置路径。例如。

    dist/
         index.html
         bundle/
              bundle.js
              bundle.css
    

    在这种情况下,它将是:publicPath: "./bundle"

    【讨论】:

    • publicPath: "/static/" 是什么意思?在生产中,webpack 将生成一个/static/ 文件夹,其中包含bundle.jsbundle.css?另外,我拥有的.jpg, .png 图像呢?他们会住在哪里?
    • 如果你有 Webpack file-loader 插件并且你确实导入了像 import img from './file.png'; 这样的图像资源,那么它们也应该存在于 output: path 所在的位置
    【解决方案2】:

    pubicPath 是您的 index 寻找资源的地方,因此它必须与您的服务器公开资源(css、图像、字体等)相同,例如:

    如果您的 serverhttp://localhost:8080/ 一样在 8080 上运行您的应用,并且您的索引中有此行:

    <link rel='stylesheet' href='/static/bundle.css' />
    

    您的服务器必须在收到/static 请求时为bundle.css 和其他资源提供服务

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 2017-08-07
      • 2016-12-13
      • 2011-11-25
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多