【问题标题】:Error using partials with HTML Webpack Plugin使用带有 HTML Webpack 插件的部分时出错
【发布时间】:2018-05-26 08:45:49
【问题描述】:

我正在尝试使用 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) 模块解析失败:意外令牌 (1:2) 你可能需要一个合适的加载器来处理这个文件类型。”

【问题讨论】:

    标签: javascript html webpack


    【解决方案1】:

    编辑

    (编辑:2017-12-20 将“loaders”移至“rules”)

    默认情况下,“html-webpack-plugin”将模板解析为“underscore”(也叫lodash)模板,你的“template.html”没有错,错误是webpack failed to resolve 'html -loader' 用于您的“template.html” &lt;%= require('html-loader!./footer.html') %&gt;,所以需要为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!”来自它:

    &lt;%= require('./footer.html') %&gt;

    现在应该可以了。


    编辑发布我的代码以供参考:

    /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!");
    

    环境:

    • webpack 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”的内容已正确插入。


    老答案

    方法一: Using "es6" template

    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,它会工作的

    方法二:使用“下划线”模板

    按照“方法 1”的第 1 步和第 2 步,然后:

    • 将“template.html”重命名为“template.html.ejs”
    • 在“webpack.config.js”中将template: './src/template.html' 更改为template: './src/template.html.ejs'
    • 运行 webpack

    【讨论】:

    • 谢谢!我尝试添加它,但第 3 点似乎有一些错误(添加插值)。你确定我应该在这里调用 HtmlWebPack Plugin 而不是 Html Loader 的引用吗?
    • 这是我在运行 Webpack(或 npm run start)时在控制台中遇到的错误: ./src/footer.html 中的错误模块解析失败:意外的令牌 (1:7) 您可能需要一个合适的加载器来处理这个文件类型。 |页脚测试 | @ ./node_modules/html-loader?interpolate!./src/template.html 1:161-185
    • 从上面的页面引用 >>> 从 npm 5.0.0 开始,已安装的模块默认添加为依赖项,因此不再使用 --save 选项。其他保存选项仍然存在,并列在 npm install 的文档中
    • @Staffan Estberg 帖子已更新,我的代码供参考
    • @levipadre 你可以使用interpolate标志在“html-loader”中启用ES6模板字符串的插值语法,webpack.config.js的规则如下:rules: [ { test: /\.html$/, loader: [{ loader: 'html-loader', options: { interpolate: true } }] } ],,然后使用ES6模板来需要一个 html 文件${ require('../snippets/country-selector.html') }。祝你好运!
    猜你喜欢
    • 2020-11-27
    • 2023-03-13
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2017-02-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多