Я запускаю приложение с Node, Express.js, Webpack и Handlebars. Я искал ответ вокруг, но никто не помог. Вот моя файловая структура.
Handlebars (top folder)
dist
bundle.js
node_modules
routes
src
css
input-elements.css
main.css
js
app.js
dom-loader.js
server.js
index.html
package.json
package-lock.json
webpack.config.js
Я знаю, что Express вытягивает из нужных мест в моем файле server.js:
const hbs = require('express-handlebars');
const path = require('path');
const express = require('express');
const app = express();
const port = 8080;
app.set('port', port || 9001);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../index.html'));
});
app.use(express.static(path.resolve('dist')));
app.listen(app.get('port'), function () {
console.log('Web server listening on port ' + app.get('port'));
});
Вот мой webpack.config.js:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.join(__dirname, './src/js/app.js'),
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
};
И мой index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Webpack 2 Basics</title>
<script type="text/javascript" src="../dist/bundle.js"></script>
</head>
<body>
<h1>Let's learn Webpack 2</h1>
<button id="secret-button">Show the Secret</button>
<p id="secret-paragraph">You can't see this all the time</p>
</body>
</html>
Вот мой package.json:
{
"name": "handlebars",
"version": "1.0.0",
"description": "",
"main": "./src/js/app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "concurrently \"webpack -p\" \"nodemon ./src/js/server.js --ext html,scss,css,js,json\""
},
"author": "",
"license": "ISC",
"devDependencies": {
"concurrently": "^4.0.1",
"css-loader": "^1.0.0",
"express": "^4.16.3",
"express-handlebars": "^3.0.0",
"nodemon": "^1.18.4",
"style-loader": "^0.23.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0"
}
}
Я могу подтвердить, что Webpack собирает пакет. В браузере есть две ошибки:
#1: Failed to load resource: the server responded with a status of 404 (not
found) --> referring to bundle.js
#2: Refused to execute script from 'http://localhost:8080/dist/bundle.js'
because its MIME type ('text/html') is not executable, and strict MIME type
checking is enabled.
Express отправляет мой файл index.html, но не отправляет пакет вместе с ним. У меня есть файл app.use ( bundle.js ) в моем файле server.js, но по какой-то причине он не отправляется. Что-то не так с моим путем?
Это связано с тем, что я использую здесь абсолютные пути вместо относительных? Если да, то лучше ли использовать модуль пути здесь?
Буду признателен за любую помощь.