我只是试图加载HTML文件,因此可以将其用作react中的组件。 我已经尝试过在webpack.config.js中进行各种配置,已经尝试重新安装html-loader,并且查看了我能找到的所有教程/错误文章,都没有运气解决我的问题。
webpack.config.js
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
},
package.json
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"@babel/preset-react": "^7.0.0",
"classnames": "^2.2.6",
"css-loader": "^2.1.0",
"html-loader": "^0.5.5",
"style-loader": "^0.23.1",
"webpack": "^4.19.1",
"webpack-cli": "^3.2.1"
},
"babel": {
"presets": [
"@babel/env",
"@babel/react"
]
}
index.jsx
import test from './test.html'
错误
./src/test.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> <h1>Hello, world!</h1>
答案 0 :(得分:0)
您的webpack.config.js必须像这样
webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: [path.resolve(__dirname, './index.js')],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
},
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/react']
}
},
resolve: { extensions: [".js", ".jsx"] }
}
]
}
}
package.json
{
"name": "wb",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"scripts": {
"build": "webpack --config ./webpack.config.js --mode development "
},
"author": "",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"@babel/preset-react": "^7.0.0",
"classnames": "^2.2.6",
"css-loader": "^2.1.0",
"html-loader": "^0.5.5",
"style-loader": "^0.23.1",
"webpack": "^4.19.1",
"webpack-cli": "^3.2.1"
},
"dependencies": {
"react": "^16.6.3",
"react-dom": "^16.6.3"
}
}
tm.html
<h1>hi test </h1>
<p>test test</p>
index.js
import tm from './tm.html'
document.write(tm)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<body>
<script src="dist/app.bundle.js"></script>
</body>
</html>