javascript - 请教下webpack+node express的使用

 奇丶葩故事会 发布于 2022-11-14 05:21

在写组件的时候,会区分开发和生产环境,在webpack中使用插件html-webpack-plugin实现动态生成html文件,使用node 的express搭建一个服务器,webpack的代码如下:
生产环境下:

config.plugins = [
    // 提取css为单文件
    new ExtractTextPlugin("../[name].[contenthash].css?1.2.1"),

    new HtmlWebpackPlugin({
        filename: '../index.html',
        template: path.resolve(__dirname, '../src/index.html'),
        inject: true
    })
];

开发环境下:

config.plugins = [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
            filename: 'src/index.html',
            template: path.resolve(__dirname, '../src/index.html'),
            inject: true
        })
];
请教下: HtmlWebpackPlugin中的filename 为什么不是一样的,最后访问localhost:8080必须加上/src才能看到对应的页面,是什么原因??

1 个回答
  • 直接带你去看 HtmlWebpackPlugin 源码吧
    https://github.com/ampedandwi...

    path.relative(compiler.options.output.path, filename);

    https://nodejs.org/api/path.h...

    The path.relative() method returns the relative path from from to to. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.

    以你的配置中的output路径开始,匹配出一个绝对路径,举个例子

    > path.relative('./dist', 'index.html')
    '../index.html'
    > path.relative('./dist', '../index.html')
    '../../index.html'

    这解释了为什么filename不一样,会导致生成的文件的位置不一致。

    而为什么要那么配置,我猜可能是想在打包的时候把index.html作为主入口放在项目根目录,把静态资源文件放到一个目录。

    而你的开发配置再我看来就是配错了。

    一个小问题,能扯这么久,我也佩服我自己,可能是加班加多了,脑袋有点晕吧

    2022-11-14 06:09 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有