【发布时间】:2019-09-21 12:37:35
【问题描述】:
问题背景
我有 webpack 用于将我的打字稿编译成 javascript。当我更改我的打字稿代码时,自动重新加载工作。但是,webpack 并没有看我的静态 html 文件。
.
├── dist
│ ├── index.html
│ └── style.css
├── src
│ └── index.ts
└── webpack.config.js
问题是我需要在我的index.html 中进行一些更改,而 webpack 不会自动检测这些更改。而且,如果我刷新 html 页面,它似乎会破坏 webpack 的 webpack-dev-server。
预期输出
我希望所有内容都在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>
我的index.ts 包含:
import './index.html';
我尝试了什么
起初我尝试将我的 css 的导入添加到我的index.ts:
import './style.css';
但这不起作用。接下来我查看了 html-loader 文档,它似乎暗示了我在寻找什么:
但是,我已经读过这样的内联加载程序已被弃用,并且通过源代码查看似乎没有任何用于插值的配置选项。无论如何,我尝试按照文档中的描述进行操作,但它要么根本不起作用,要么给我一些关于 require not found 的错误消息(虽然我似乎无法重现该错误)。我的index.html 包含:
<link rel="stylesheet" href="${require(`style.css`)">
和index.ts 包含:
require("html-loader?interpolate=require!./index.html");
如何让 webpack 将我的 style.css 移动到 dist 文件夹?
我有预感我误解了 webpack 应该如何使用。当我有工作时,我可以在代码审查堆栈交换上发布我的 webpack 配置,以获得创建更惯用的 webpack 配置的帮助吗?
【问题讨论】:
-
你看过stackoverflow.com/questions/48041902/…吗?似乎是一个类似的问题。
标签: html webpack static-html