Javascript 网页包错误无法解决'/src&x27;
我是新来的网页包。我正在学习react并使用webpack为其构建环境 我有webpack-config.jsJavascript 网页包错误无法解决'/src&x27;,javascript,reactjs,npm,webpack,command-line-interface,Javascript,Reactjs,Npm,Webpack,Command Line Interface,我是新来的网页包。我正在学习react并使用webpack为其构建环境 我有webpack-config.js var path = require('path'); module.exports = { mode: 'production', entry: './script.js', output: { path: path.resolve(__dirname, 'src'), filename: 'transpiled.
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']
}
}
]
}
}
和script.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello world</h1>
document.getElementByIdName('first')
);
但是,当我使用“npm run it”运行npm时,它会显示
配置中的警告
尚未设置“模式”选项。将“模式”选项设置为“开发”或“生产”,以启用此环境的默认设置。
多开发服务器/客户端出错?webpack/hot/dev服务器。/src
未找到模块:错误:无法解析D:\React Js\LearnReact'@multi-dev derver/client中的“./src”?webpack/hot/dev服务器。/src
i?wdm?:未能编译
请帮助我,我真的被卡住了,想知道解决方案。您需要将
--config
选项添加到webpack dev server
:
webpack dev server--config path/to/webpack.config.js
在基本配置中将模式设置为development
,以后进行生产构建时可以覆盖该模式
还要确保/script.js
文件位于项目的根目录中,即包.json
旁边,因为此文件路径与npm
脚本执行相关
基于此配置-->path:path.resolve(uu dirname,'src')
所有构建的资产都将位于项目根目录下的src
文件夹中,假设该文件夹是webpack.config.js
文件所在的位置(此路径与配置文件相对)。实际文件夹将仅在生产
中生成,在开发
中,资产存储在内存中
您可能还需要设置一个publicPath
:
output: {
...
publicPath: '/'
}
我还建议使用html网页包插件
,因为这可以为您解析到js文件的正确路径
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
})
]
然后,您不必包含脚本的路径,因此您的html文件如下所示:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="first"></div>
</body>
</html>
是否创建了src
文件夹?是否加载了网页配置文件?如果我没记错,您必须在npm脚本中指定,或者使用默认名称webpack.config.js
。看看这些文件
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
})
]
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="first"></div>
</body>
</html>