我正在通过webpack开始我的学习之旅,但我遇到了一个问题,我认为这是由extract-loader
引起的。当webpack获取我的HTML文件时,似乎无法正确编译,导致在使用import.meta
时出现错误。我认为这个错误并不是真正的错误,而是表明我对webpack及其加载器如何工作的理解存在问题。能否有人查看我的文件,看看是否发现了错误?
我使用的是node v15.12.0和npm v7.6.3。
非常感谢。
package.json
{
"devDependencies": {
"css-loader": "^5.2.0",
"extract-loader": "^5.1.0",
"file-loader": "^6.2.0",
"html-loader": "^2.1.2",
"style-loader": "^2.0.0",
"webpack": "^5.28.0",
"webpack-cli": "^4.5.0"
}
}
webpack.config.js:
const path = require('path')
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/dist'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.html$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].html'
}
},
'extract-loader',
'html-loader'
]
}
]
}
}
src/main.js
require('./style.css')
require('./index.html')
src/style.css:
body {
margin: 0;
}
src/index.html
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Hello world!</h1>
<script src="main.js"></script>
</body>
</html>
Webpack输出:
$ npx webpack
asset bundle.js 19.6 KiB [compared for emit] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 8.95 KiB
modules by path ./src/ 737 bytes
modules by path ./src/*.css 651 bytes
./src/style.css 326 bytes [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./src/style.css 325 bytes [built] [code generated]
./src/main.js 47 bytes [built] [code generated]
./src/index.html 39 bytes [built] [code generated] [1 error]
modules by path ./node_modules/ 8.23 KiB
./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]
./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]
ERROR in ./src/index.html
Module build failed (from ./node_modules/extract-loader/lib/extractLoader.js):
SyntaxError: unknown: Unexpected token (3:54)
1 | // Imports
2 | import ___HTML_LOADER_GET_SOURCE_FROM_IMPORT___ from "../node_modules/html-loader/dist/runtime/getUrl.js";
> 3 | var ___HTML_LOADER_IMPORT_0___ = new URL("./main.js", import.meta.url);
| ^
4 | // Module
5 | var ___HTML_LOADER_REPLACEMENT_0___ = ___HTML_LOADER_GET_SOURCE_FROM_IMPORT___(___HTML_LOADER_IMPORT_0___);
6 | var code = "<!DOCTYPE html>\n<html lang=\"en\">\n<body>\n <h1>Hello world!</h1>\n <script src=\"" + ___HTML_LOADER_REPLACEMENT_0___ + "\"></script>\n</body>\n</html>\n\n";
at Parser.pp$5.raise (/home/jdferreira/Repositories/Temps/extract-loader-issue/node_modules/babylon/lib/index.js:4454:13)
html
文件是做什么的呢?(我猜这是您的入口点?) - tmhao2005(function (exports, require, module, __filename, __dirname) { body {
开头。 - jdferreiraindex.html
设置为索引文件,应该使用 html 插件而不是导入它。顺便说一下,请不要在 webpack 配置文件中将 html 文件设置为应用程序的入口点。 - tmhao2005