15

我正在使用 Webpack 来捆绑资源。目前,它将 CSS 和 JS 文件捆绑到一个名为 bundle.js 的单独文件中。如何将 JS 和 CSS 嵌入到 html 文件中?

import HtmlWebpackPlugin from 'html-webpack-plugin';
import {HotModuleReplacementPlugin} from 'webpack';

export default {
  entry: {app: './test/dev'},
  module: {
    loaders: [
      {test: /\.js/, loader: 'babel-loader', exclude: /node_modules/},
      {test: /\.scss$/, loader: 'style!css!sass'}
    ]
  },
  plugins: [new HotModuleReplacementPlugin(), new HtmlWebpackPlugin()],
  devtool: 'eval-source-map'
};
4

3 回答 3

7

使用react-dev-utils 中InlineChunkHtmlPlugin

const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');

module.exports = {
  // ...
  output: { filename: 'client-bundle.js' },
  plugins: [
    new HtmlWebpackPlugin(),
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/client-bundle/]),
  ],
  // ...
};

*where "/client-bundle/"正则表达式应该匹配输出文件名

https://github.com/facebook/create-react-app/tree/master/packages/react-dev-utils#new-inlinechunkhtmlpluginhtmlwebpackplugin-htmlwebpackplugin-tests-regex


对于内联CSS,您需要额外的规则对象:

module.exports = {
  entry: ['./src/style.css', './src/client.js'],
  // ...
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          'style-loader', // Creates `style` nodes from JS strings
          'css-loader', // Translates CSS into CommonJS
        ],
      },
    ],
  },
}
于 2021-01-09T20:47:51.017 回答
5

使用https://github.com/DustinJackson/html-webpack-inline-source-plugin

plugins: [
  new HtmlWebpackPlugin({
    inlineSource: '.(js|css)$' // embed all javascript and css inline
  }),
  new HtmlWebpackInlineSourcePlugin()
]  
于 2017-07-24T09:03:57.440 回答
0

html-webpack-inline-source-plugin 不再起作用,您可以使用 script-ext-html-webpack-plugin 代替。

const HtmlWebpackPlugin = require('html-webpack-plugin')
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: __dirname + '/dist',
    },
    plugins: [
        new HtmlWebpackPlugin({
            cache: false
        }),
        new ScriptExtHtmlWebpackPlugin({
            inline: [/\.js$/],
        })
    ]
}

于 2020-10-28T14:35:27.740 回答