sabx score 179
2018/11/13 09:05 投稿
[Webpack] buildでエラーにならないのですが、Chromeコンソールを開くとエラーが表示される |
### 聞きたいこと |
webpackでビルドした後に、webpack-dev-serverを起動すると、Chromeコンソールにエラーが下のように表示されます。 |
- エラー |
``` |
Uncaught ReferenceError: require is not defined |
at Object.events (external "events":1) |
at __webpack_require__ (bootstrap:19) |
at Object../node_modules/depd/lib/compat/index.js (index.js:14) |
at __webpack_require__ (bootstrap:19) |
at Object../node_modules/depd/index.js (index.js:11) |
at __webpack_require__ (bootstrap:19) |
at Object../node_modules/body-parser/index.js (index.js:14) |
at __webpack_require__ (bootstrap:19) |
at Object../node_modules/express/lib/express.js (express.js:15) |
at __webpack_require__ (bootstrap:19) |
``` |
実装したファイルは下の通りです。 |
- package.json |
``` |
{ |
"name": "test", |
"version": "1.0.0", |
"description": "", |
"main": "index.js", |
"scripts": { |
"test": "echo \"Error: no test specified\" && exit 1", |
"build": "webpack", |
"dev": "webpack-dev-server --open" |
}, |
"author": "", |
"license": "MIT", |
"devDependencies": { |
"babel-core": "^6.26.3", |
"babel-loader": "^7.0.4", |
"babel-preset-env": "^1.7.0", |
"express": "^4.16.3", |
"webpack": "^4.20.2", |
"webpack-cli": "^3.1.1", |
"webpack-dev-server": "^3.1.10" |
} |
} |
``` |
- webpack.config.json |
``` |
const path = require('path'); |
module.exports = { |
context: __dirname + '/src', |
mode: 'development', |
entry: { |
js: './src/js/main.js', |
}, |
output: { |
path: path.join(__dirname, 'public/js'), |
filename: 'bundle.js' |
}, |
module: { |
loaders: [{ |
test: /\.js$/, |
loader: 'babel-loader', |
exclude: /node_modules/, |
query: { presets: ['es2015', 'stage-0'] } |
}] |
} |
} |
``` |
- main.js |
``` |
import express from 'express' |
const app = express() |
app.get('/', (req, res) => res.send('Hello World!')) |
app.listen(3000, () => console.log('Example app listening on port 3000!')) |
``` |
- index.html |
``` |
<!DOCTYPE html> |
<html> |
<head> |
<meta charset="utf-8"> |
<title>Super Mario</title> |
</head> |
<body> |
<script src="./js/bundle.js"></script> |
</body> |
</html> |
``` |
また、ディレクトリ構成は以下の通りです。 |
``` |
project/ |
├ node_module/ |
├ public/ |
├ js/ |
│ └ bundle.js |
└ index.html |
├ src/ |
│ └ js/ |
│ └ main.js |
├ package-lock.json |
└ package.json |
``` |
``` |
すいませんが、情報が不足していましたらコメントお願いいたします。 |