webpack html文件link css 绝对路径

新手上路,请多包涵

我在尝试一个多页面的时候,写了2个组件,里面包含index.html | style.css | index.js,对于 JS 文件,我可以通过插件和 entry 入口去解决引用问题。

但是对于 CSS 文件,我这里2个组件,分别使用的是 JS 中引入require('./style.css') 和直接在 HTML 中link src="./style.css",通过require引入的 CSS 通过 Mini 插件能引入,另一个组件打包后的 HTML 文件中,仍然存在 link src="./style.css",而此时打包路径已经变了,因此会引入失败。

请问一下通过link scr="./style.css"的 CSS 文件是如何打包的,保证能正常引用?

打包后的 HTML 文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>BAR</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div id="hello">Hello BAR!</div>
    <div id="test">BAR 页面</div>

    <textarea name="" id="" cols="30" rows="10">
        输入BAR
    </textarea>
<script type="text/javascript" src="../js/bar.c724a7f5b19aaaf30e5b.js"></script></body>
</html>

阅读 4.5k
2 个回答

通过 html-webpack-plugin 的模板参数修改css路径试一下:

// webpack.config.js
plugins: [
  new htmlWebpackPlugin({
    filename: 'index.html',
    template: path.join(__dirname, '../src/index.html'),
    templateParameters: {
      'path': './style.css'
    },
  }),
],

html模板:

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