I am new to webpack. I am learning react and building environment for it using webpack.
I have webpack-config.js
var path = require('path');
module.exports = {
mode: 'production',
entry: './script.js',
output:
{
path: path.resolve(__dirname, 'src'),
filename: 'transpiled.js'
},
module:
{
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query:
{
presets: ['es2015','react']
}
}
]
}
}
and script.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello world</h1>
document.getElementByIdName('first')
);
and index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="first"></div>
<script src="transpiled.js"></script>
</body>
</html>
in Pakage.json file I have written
"scripts": {
"it": "webpack-dev-server --hot"
},
But when i run the npm with "npm run it" , it shows me the error of
WARNING in configuration The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment. ERROR in multi -dev-derver/client? http://localhost:8080 webpack/hot/dev-server ./src Module not found: Error : Cant resolve './src' in D:\\React Js \\LearnReact' @multi -dev-derver/client? http://localhost:8080 webpack/hot/dev-server ./src i ?wdm?: failed to Compile.
Please help me i am really stuck and want to know the solution.
You need to add pass the --config
option to webpack-dev-server
:
webpack-dev-server --config path/to/webpack.config.js
Also set your mode to development
in your base config, you can overwrite it later when you do a production build.
Also ensure that your ./script.js
file is in the root of your project, ie next to your package.json
since this file path is relative to the npm
script execution.
Based on this configuration --> path: path.resolve(__dirname, 'src')
all your built assets will end up in a src
folder in the root of your project, assuming that is where your webpack.config.js
file is (this path is relative to your config file). The actual folder will only be generated in production
, in development
assets are stored in memory.
You might also want to set a publicPath
:
output: {
...
publicPath: '/'
}
I would also recommend using the html-webpack-plugin
since this can resolve the correct paths to your js file for you.
var HtmlWebpackPlugin = require('html-webpack-plugin');
...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html', // name of file that will be outputted to 'src' when built
template: // path to your html file relative to config
inject: true
})
]
Then you don't have to include the path to your script, so your html file would look like:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="first"></div>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.