【问题标题】:Using Webpack HtmlWebpackPlugin使用 Webpack HtmlWebpackPlugin
【发布时间】:2017-09-09 19:00:37
【问题描述】:

我对 webpack 和其他东西很陌生,我需要一个解决方案来分离 index.htmlbase hrefbundle.js src >,用于开发和生产,因为两者是不同的。

用于发展

基础 href = 本地主机

src = /bundle.js

用于生产

基本 href = 服务器网址

src = /dist/bundle.js

为了解决上述问题我尝试使用HtmlWebpackPlugin,下面是webpack.config.js设置

var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname + "/dist",
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
    {
     exclude: /node_modules/,
     use:[
      {
      loader: 'babel-loader',
      options:{
          presets: ['react', 'es2015', 'stage-1']
       }
      },
     ]
  },
  plugins: [
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
       }),
       new HtmlWebpackPlugin({
          template:'index.html',
          inject:'head',
          hash: true,
          baseHref: 'http://localhost:8030/'
      })
  ]
};

以下是我尝试将 baseHref 用于index.html

的方式
<html>
  <head>
    <% if (htmlWebpackPlugin.options.baseHref) { %>
      <base href="<%= htmlWebpackPlugin.options.baseHref %>">
    <% } %>

    /*
       Several css are defined with relative path here
    */
  </head>
  <body>
    <div class="container-fluid"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

使用上述设置我收到以下错误

我需要帮助才能知道我在这里做错了什么?

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 是否安装了html-loader
  • 不,它没有安装,这有什么区别@Prakashsharma 吗?
  • 我会说改用ejs 模板。你不需要任何装载机。 github.com/jantimon/html-webpack-plugin/blob/master/docs/…
  • 链接说如果你使用 html 模板,那么你需要html-loader
  • 我修复了它,问题是缺少test: /\.js$/, for babel-loader 它适用于html,但我现在改为ejs。感谢您的帮助。

标签: javascript reactjs webpack html-webpack-plugin


【解决方案1】:

https://github.com/jantimon/html-webpack-plugin/issues/212

Github 上的这个问题建议将“index.html”文件重命名为“index.ejs”。

这似乎是因为 webpack 试图将 Babel 转译器应用到您的 html 文件并且失败,“.ejs”扩展名会阻止它。

【讨论】:

  • 我修复了它,问题是缺少test: /\.js$/, for babel-loader 它适用于html,尽管我现在改为ejs。感谢您的帮助。
  • 我本来打算这样做,但你的配置没有 babel-loader!
【解决方案2】:

HtmlWebpackPlugin 的主要目的是识别您的入口文件并将它们放置在适当的位置(dist/index.html)。所以你不需要手动操作。

如果您没有HtmlWebpackPlugin,您应该记住您在应用程序中使用的每个文件并手动将它们添加到index.html

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 2017-12-29
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 2019-03-15
    • 2018-10-03
    相关资源
    最近更新 更多