请教下webpack+node express的使用

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

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

    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才能看到对应的页面,是什么原因??

阅读 3.3k
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作为主入口放在项目根目录,把静态资源文件放到一个目录。

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

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题