Webpack 将 js/css 文件内容直接注入 index.html [英] Webpack inject js/css file content directly to index.html
本文介绍了Webpack 将 js/css 文件内容直接注入 index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的代码
<html>
<head>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="path_to_css/some_css.css" rel="stylesheet" type="text/css">
</head>
<body>
...
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="jquery/jquery.min.js"></script>
</body>
</html>
我需要插件/加载程序或其他方式来获取我的 html 文件,并将链接和脚本标签替换为该文件的内容,有什么办法可以做到吗?
and I need plugin/loader or other way to get my html file with replaced link and script tags to content of this files, is there any way to do it?
最后我写了自己的插件来满足我的需求include-file-webpack-plugin
Finnaly i wrote own plugin which fit my needs include-file-webpack-plugin
推荐答案
实际上可以通过:
npm i --save-dev css-loader to-string-loader
使用
npm i --save-dev css-loader to-string-loader
configure your webpack with
module: [
rules: [
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader']
}
]
}
然后在你的项目中你可以像这样访问css作为字符串
Then in your project you can access the css as string like so
const cssContent= require('path_to_css/some_css.css');console.log('你的 css 是:', cssContent.toString());
或者你想手动将它注入页面:
Or maybe you want inject it manually to the page with:
const boostrap= require('bootstrap/dist/css/bootstrap.min.css');
let style= document.createElement('style');
style.id= 'boostrap';
style.setAttribute('type', 'text/css');
style.innerHTML= boostrap.toString();
document.body.appendChild(style);
参考
这篇关于Webpack 将 js/css 文件内容直接注入 index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文