【问题标题】:When using Webpack, which folder do I have my server statically serve?使用 Webpack 时,我的服务器静态服务于哪个文件夹?
【发布时间】:2016-09-24 02:52:02
【问题描述】:

假设我想(我的老板让我)使用 webpack,并且我的文件结构如下:

其中builds 是webpack 输出捆绑/编译src 文件夹的结果的位置,如果它存在于服务器上,我如何让index.html 指向bundle.js,即我要公开哪个文件夹通过express.static()?什么是正确的“webpack”方式来做到这一点,即一个简单的webpack.config,如下所示?我是否缺少有关其工作原理的一些基本知识?理想情况下,我想在我的 index.html

中执行以下操作
<html>
<script src='bundle.js'></script> 
<!-- bundle.js spits a bunch of CSS into the html, dynamically builds elements, etc -->
</html>

或者这不是 webpack 中的工作方式?

webpack.config.js

module.exports = {
    entry:  './src/index.js',
    output: {
        path:     'builds',
        filename: 'bundle.js',
    },
    module: {
        loaders: [
            { test: /\.css$/, 
              loader: "style!css" 
            }
        ]
    }
};

我试图通过the docsthis oft-linked article 解决这个问题。

【问题讨论】:

    标签: javascript html webpack


    【解决方案1】:

    由于不将任何目录结构暴露给最终用户是一种很好的做法,因为它为 Web 开发创造了机会,因此带有 express 的 nodejs 有一种机制来处理这个问题。你可以做的就是以这种方式暴露你的 webpack

    app.use('/buidscript', express.static(__dirname + '/builds/'));
    

    然后,来自/buidscript/bundle.js 的任何浏览器请求都将自动从您的构建目录中获取。

    <script src='/buidscript/bundle.js'></script> 
    

    现在你可以围绕这个收集你的想法,以任何你想要的方式来实现它。

    您正在寻找的理想案例

    app.use(express.static(__dirname + '/builds'));
    

    现在你可以使用了

    <script src='bundle.js'></script> 
    

    因为任何请求 bundle.js 都会在暴露的静态构建目录中搜索

    将其添加到 package.json 的脚本中

    “scripts”: {
     “start”: “webpack-dev-server --content-base build/ --inline --hot”,
     ...
     }
    // Use it by running 
    $ npm start
    

    现在这将在开发模式下运行 index.html 之前构建你的 bundle.js。

    --content-base build/ 
    

    将在您的构建文件夹中提供静态文件。那么你就可以直接使用 bundle.js 了。它将查找任何文件更改并重新编译 bundle.js

    【讨论】:

    • 是的,这正是我的意思。如果我公开/builds,那么客户端可以访问bundle.js。但是,index.html 不能,如果我服务器 index.html,它无权访问 bundle.js
    • 如果我同意你的建议,我会部署一个builds 文件夹,其中包含我的index.html 文件的副本,然后部署服务器也会在其中添加一个bundle.js 文件.
    • 我还是不明白为什么 index.html 不能访问 bundle.js 。使用 webpack 时,您必须区分开发环境和生产环境。查看更新的答案
    • 因为index.html/src里面,而不是/build里面
    • 所以GET 请求root/index.html 将导致cannot GET,因为index.html 将无法公开访问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2017-03-09
    • 2013-12-08
    • 2020-05-18
    • 2020-05-19
    • 1970-01-01
    相关资源
    最近更新 更多