如何使用 HtmlWebpackPlugin 将已编译的 Stylus 包注入 html 文件?

How to inject a compiled Stylus bundle into html file using HtmlWebpackPlugin?

我需要将 Stylus 包注入 webpack 配置文件中的 html 文件。

我已经使用 HtmlWebpackPlugin 注入了 js 包,我认为也可以使用这个插件注入一个编译好的手写笔包。

下面是我当前的 webpack.config.js 文件:

var HtmlWebpackPlugin = require('html-webpack-plugin');

var HtmlWebpackPluginConfigForJS = new HtmlWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
var HtmlWebpackPluginConfigForStyles = new HtmlWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.styl',
    inject: 'head'
});

module.exports = {
    entry: [
        'babel-polyfill',
        './app/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        filename: 'index_bundle.js'
    },
    devtool: 'source-map',
    cache: true,
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader'
            },
            {
                test: /\.styl$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'style-loader!css-loader!stylus-loader'
            }
        ]
    },
    plugins: [
        HtmlWebpackPluginConfigForJS,
        HtmlWebpackPluginConfigForStyles
    ],
    stylus: {
        use: [require('nib')(), require('rupture')()],
        import: ['~nib/lib/nib/index.styl', '~rupture/rupture/index.styl']
    }
}

我获得样式的唯一方法是在我的 javascript 文件中添加 require('./index.styl);,但这不是我需要的。

HtmlWebpackPluginConfigForJS 工作正常并成功地将 index_bundle.js 文件注入到我的 index.html 中。但它不适用于样式。


你能帮我改进我的 webpack 配置,让它正确地注入我的手写笔包吗?

默认情况下,HtmlWebpackPlugin 注入 css 个文件,来自文档:

If you have any css assets in webpack's output (for example, css extracted with the ExtractTextPlugin) then these will be included with tags in the HTML head.

因此您可以使用 ExtractTextPlugin 将所有样式提取到一个或多个文件中。但是要提取你应该在你的主要 index.js 中要求你的 index.styl 以便加载程序可以看到并进行提取。