我使用Webpack捆绑资源。目前,它将CSS和JS文件捆绑到一个名为bundle.js的单独文件中。如何在JS文件中嵌入JS和CSS嵌入内联?
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'
};
答案 0 :(得分:6)
使用来自 react-dev-utils
的 InlineChunkHtmlPluginconst 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/" 正则表达式应该匹配输出文件名
对于内联 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
],
},
],
},
}
答案 1 :(得分:2)
使用https://github.com/DustinJackson/html-webpack-inline-source-plugin
plugins: [
new HtmlWebpackPlugin({
inlineSource: '.(js|css)$' // embed all javascript and css inline
}),
new HtmlWebpackInlineSourcePlugin()
]
答案 2 :(得分: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$/],
})
]
}