[英]webpack error cant resolve './src'
我是webpack的新手。 我正在學習使用webpack反應並為其構建環境。
我有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']
}
}
]
}
}
和script.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello world</h1>
document.getElementByIdName('first')
);
和index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="first"></div>
<script src="transpiled.js"></script>
</body>
</html>
在我寫的Pakage.json文件中
"scripts": {
"it": "webpack-dev-server --hot"
},
但是當我使用“ npm run it”運行npm時,它顯示了以下錯誤
配置中的警告尚未設置“模式”選項。 將“模式”選項設置為“開發”或“生產”以啟用該環境的默認設置。 多-dev-derver /客戶端中的錯誤? http:// localhost:8080 webpack / hot / dev-server ./src找不到模塊:錯誤:無法在D:\\ React Js \\ LearnReact'@multi -dev-derver / client中解析'./src'嗎? http:// localhost:8080 webpack / hot / dev-server ./src i?wdm ?:編譯失敗。
請幫助我,我真的很困惑,想知道解決方案。
您需要將--config
選項傳遞給webpack-dev-server
:
webpack-dev-server --config path/to/webpack.config.js
還要在基本配置中將模式設置為development
模式,稍后在進行生產構建時可以覆蓋它。
還要確保您的./script.js
文件位於項目的根目錄下,即package.json
旁邊,因為該文件路徑與npm
腳本執行有關。
根據此配置-> path: path.resolve(__dirname, 'src')
,假設您的webpack.config.js
文件位於( webpack.config.js
目錄下,則所有已構建資產最終都將位於項目根目錄下的src
文件夾中。此路徑相對於您的配置文件)。 實際的文件夾僅在production
中生成,在development
資產中存儲在內存中。
您可能還需要設置publicPath
:
output: {
...
publicPath: '/'
}
我還建議您使用html-webpack-plugin
因為這樣可以為您解析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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.