如何在带有webpack的静态html页面中导入静态资产?
问题背景 我有一个用于将我的typescript编译成javascript的网页包。当我更改typescript代码时,自动重新加载会起作用。但是,webpack没有监视我的静态html文件如何在带有webpack的静态html页面中导入静态资产?,html,webpack,static-html,Html,Webpack,Static Html,问题背景 我有一个用于将我的typescript编译成javascript的网页包。当我更改typescript代码时,自动重新加载会起作用。但是,webpack没有监视我的静态html文件 . ├── dist │ ├── index.html │ └── style.css ├── src │ └── index.ts └── webpack.config.js 问题是我需要在我的index.html中做一些更改,而webpack不会自动检测到这些更改。而且,如果我刷新html
.
├── dist
│ ├── index.html
│ └── style.css
├── src
│ └── index.ts
└── webpack.config.js
问题是我需要在我的index.html
中做一些更改,而webpack不会自动检测到这些更改。而且,如果我刷新html页面,它似乎会破坏webpack的webpack dev服务器
预期产出
我希望一切都在src
文件夹中,当我运行webpack
时,我的dist
文件夹中有一个完全工作的静态站点。即:
. .
├── dist ├── dist
├── src │ ├── index.html
│ ├── index.html │ ├── bundle.js
│ ├── index.ts npx webpack -> │ └── style.css
│ └── style.css ├── src
└── webpack.config.js │ ├── index.html
│ ├── index.ts
│ └── style.css
└── webpack.config.js
dist
文件夹中的文件可能具有哈希文件名。不过我现在不担心这一步。我希望webpack会浏览我的文件,并确保它们链接到正确的资源。因此,如果webpack给style.css
一个哈希名称,则index.html
中的href将被更新
电流输出
我当前的解决方案同时输出index.html
和bundle.js
,但我无法将style.css
复制到dist
文件夹中。我当前的webpack.config.js
如下所示:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
mode: 'development',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.html$/,
use: [
{ loader: 'file-loader?name=[name].[ext]' },
{ loader: 'extract-loader' },
{ loader: 'html-loader' }
]
}
]
},
plugins: [
new CleanWebpackPlugin()
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
我的index.html
如下所示:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>stuff</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./bundle.js" charset="utf-8"></script>
</body>
</html>
我尝试的
起初,我尝试将css的导入添加到我的index.ts
:
import './style.css';
但这并不奏效。接下来,我查看了html加载程序文档,它似乎暗示了我在寻找什么:
然而,我已经读到像这样的内联加载程序是不推荐的,并且通过源代码查看,似乎没有任何插值配置选项。无论如何,我试图按照文档中的描述来做,但它要么根本不起作用,要么给了我一些关于require
notfound的错误消息(尽管我似乎无法重现该错误)。我的index.html
包含:
<link rel="stylesheet" href="${require(`style.css`)">
require("html-loader?interpolate=require!./index.html");
如何让webpack将我的style.css
移动到dist文件夹
我有预感我误解了webpack应该如何使用。当我有工作时,我可以在代码复查堆栈交换上发布我的网页包配置,以获得创建更惯用的网页包配置的帮助吗
const plugins = () => {
const result = [
new HtmlWebpackPlugin({
template: "./index.html", // this file will be used as html and all css/js will be automaticly included
})
]}
const plugins = () => {
const result = [
new HtmlWebpackPlugin({
template: "./index.html", // this file will be used as html and all css/js will be automaticly included
})
]}