簡體   English   中英

將部分與 HTML Webpack 插件一起使用時出錯

[英]Error using partials with HTML Webpack Plugin

我正在嘗試使用 HTML Webpack 插件創建帶有靜態 HTML 部分的設置,但遇到了一些錯誤。 這是我當前的配置:

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssets = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

    let config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'app.js'
  },
  module: {
    loaders: [{
        test: /\.html$/,
        loader: 'html-loader'
    }],
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        use: ['css-hot-loader'].concat(ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader', 'postcss-loader'],
        })),
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: ['file-loader?context=src/assets/images/&name=images/[path][name].[ext]', {
          loader: 'image-webpack-loader',
          query: {
            mozjpeg: {
              progressive: true,
            },
            gifsicle: {
              interlaced: false,
            },
            optipng: {
              optimizationLevel: 4,
            },
            pngquant: {
              quality: '75-90',
              speed: 3,
            },
          },
        }],
        exclude: /node_modules/,
        include: __dirname,
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: './src/template.html.ejs'
    }),
    new ExtractTextWebpackPlugin('main.css')
  ],
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
    historyApiFallback: true,
    inline: true,
    open: true
  },
  devtool: 'eval-source-map'
}

module.exports = config;

if (process.env.NODE_ENV === 'production') {
  module.exports.plugins.push(
    new webpack.optimize.UglifyJsPlugin(),
    new OptimizeCSSAssets()
  );
}

template.html.ejs (位於./src下)

<%=require('./header.html')%>
  <body>
    testing schmesting
  </body>
  <%=require('./footer.html')%>
</html>

(footer.html 和 header.html 位於./src下)

編輯:更新了代碼,仍然存在問題:

“錯誤中的錯誤:子編譯失敗:模塊解析失敗:意外令牌(1:0)您可能需要適當的加載程序來處理此文件類型。
SyntaxError: Unexpected token (1:0) Module parse failed: Unexpected token (1:2) 你可能需要一個合適的加載器來處理這個文件類型。”

編輯

(編輯:2017-12-20 將“裝載機”移至“規則”)

默認情況下,"html-webpack-plugin" 將模板解析為 " underscore "(也稱為 lodash)模板,你的 "template.html" 沒有錯,錯誤是由 webpack failed to resolve 'html-loader' for your "template.html" <%= require('html-loader!./footer.html') %> ,所以你需要為webpack安裝"html-loader",並配置它:

在命令行中:

npm install html-loader

並為 webpack 配置它,編輯webpack.config.js

...
module: {
    rules: [
     // ... 
        {
            test: /\.html$/, // tells webpack to use this loader for all ".html" files
            loader: 'html-loader'
        }
    ]
}

現在你可以運行“webpack”你不會看到任何錯誤,但是生成的“index.html”不是你所期望的,因為你的模板文件有“.html”擴展名,webpack現在使用“html-loader”來加載“ template.html”而不是默認的“lodash loader”,要解決這個問題,您可以將“template.html”重命名為“template.html.ejs”(或任何其他擴展名)以制作“html-webpack-plugin”回退。 除了“template.html”還有一點變化,刪除“html-loader!” 從中:

<%= require('./footer.html') %>

現在它應該工作了。


編輯發布我的代碼以供參考:

/src/template.html.ejs

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <h1>template</h1>
        <%=require('./footer.html')%>
    </body>
</html>

/src/footer.html

<footer>this is a footer</footer>

/webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

let config = {
    entry: {
        index: './src/js/index'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                loader: 'html-loader'
            }
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/template.html.ejs'
        })
    ]
}


module.exports = config;

/package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "webpack": "^3.10.0"
  }
}

/src/js/index.js

console.log("A test page!");

環境:

  • 網絡包 3.10.0
  • npm 5.6.0

運行 webpack 后“/dist/index.html”的內容:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <h1>template</h1>
        <footer>this is a footer</footer>
    <script type="text/javascript" src="index.js"></script></body>
</html>

如您所見,“footer.html”的內容已正確插入。


舊答案

方法一:使用“es6”模板

  1. 通過npm install html-loader安裝“html-loader”
  2. 將“html-loader”添加到“webpack.config.js”以加載帶有“.html”擴展名的文件,例如:
 module: { rules: [{ test: /\\.html$/, loader: 'html-loader' }], }
  1. 添加interpolate標志以啟用 ES6 模板字符串的插值語法,如下所示:
 plugins: [ new HtmlWebpackPlugin({ template: '!!html-loader?interpolate!src/template.html' }) ]
  1. 修改你的template.html以匹配 ES6 模板:
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> template </body> ${require('./footer.html')} </html>
  1. 運行webpack ,它會工作

方法 2:使用“下划線”模板

按照“方法 1”步驟​​ 1 和 2,然后:

  • 將“template.html”重命名為“template.html.ejs”
  • template: './src/template.html'更改為template: './src/template.html.ejs'中的“./src/template.html.ejs”
  • 運行 webpack

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM