如何使用 webpack 将所有内容整合到一个文件中

How to make all in one file with webpack

我需要在一个文件中创建所有内容。 我正在编写的网页将从我无法访问相对(和绝对)路径的地方提供。 所以我需要把js放在标签之间的index.html文件中。

我从 vue webpack 模板开始,将其修改为只有两个文件 - js 和 html 文件。 我可以使用 sed 等使其自动化,但有更好的方法吗?

你可以使用 webpack 插件 web-webpack-plugin , script-ext-html-webpack-plugin or html-webpack-plugin

html-webpack-plugin和extract-text-webpack-plugin方式

webpack 配置:

样本https://github.com/jantimon/html-webpack-plugin/blob/master/examples/inline/webpack.config.js

var path = require('path');
var HtmlWebpackPlugin = require('../..');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpackMajorVersion = require('webpack/package.json').version.split('.')[0];

module.exports = {
  context: __dirname,
  entry: './example.js',
  output: {
    path: path.join(__dirname, 'dist/webpack-' + webpackMajorVersion),
    publicPath: '',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-
        loader', 'css-loader') }
    ]
  },
 plugins: [
 new HtmlWebpackPlugin({
    inject: false,
    cache: false,
    filename: 'index.html',
    favicon: 'favicon.ico',
    title: 'demo'
  }),
  new ExtractTextPlugin('styles.css')
]
};

web-webpack-plugin方式

webpack 配置:

module.exports = {
  entry: {
    A: './a',
    B: './b',
  },
  plugins: [
    new WebPlugin({
        // file name or full path for output file, required.
        // pay attention not to duplication of name,as is will cover 
           other file
        filename: 'index.html',
        // this html's requires entry,must be an array.dependent resource will inject into html use the order entry in array.
        requires: {
            'inline': {
                _inline: true,
                _dist: true
            }
        }
    }),
  ]
};