gpt4 book ai didi

webpack - 使用 webpack 内联 JavaScript 和 CSS

转载 作者:行者123 更新时间:2023-12-01 17:32:09 27 4
gpt4 key购买 nike

我正在使用 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'
};

最佳答案

使用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/]),
],
// ...
};

*其中“/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
],
},
],
},
}

关于webpack - 使用 webpack 内联 JavaScript 和 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com