Module not found: Error: Can
2017-11-30 本文已影响1770人
McDu
使用 react + webpack 启动一个简单的 react 例子时, 报错 :
Module not found: Error: Can't resolve 'react' in 入口文件
Module not found: Error: Can't resolve 'react-dom' in 入口文件
一. 项目结构:
二. 一些文件内容:
app.jsx:
import React from 'react';
import ReactDom from 'react-dom';
function App() {
return (
<div>
<h1>hello world!</h1>
</div>
);
}
const app = document.createElement('div');
document.body.appendChild(app);
ReactDom.render(<App/>,app);
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev":"webpack-dev-server --hot",
"build": "webpack -w",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.17",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.5"
}
}
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');
var APP_PATH = path.resolve(ROOT_PATH, 'app');
module.exports = {
entry: {
app: path.resolve(APP_PATH, 'app.jsx')
},
output: {
path: BUILD_PATH,
filename: 'bundle_[hash:5].js'
},
devServer:{
contentBase:__dirname
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
include: APP_PATH
}
]
},
devtool: 'eval-source-map',
resolve: {
extensions: ['.js', '.jsx'],
modules: [APP_PATH, 'node_modules']
// 之前是这样写的: modules: [APP_PATH] 所以找不到 module 模块
},
plugins: [
new HtmlWebpackPlugin({
title: 'test App'
}),
new CleanWebpackPlugin(['build'])
]
};
出现错误的原因: resolve.modules 这个方法使用错了, resolve.modules 告诉 webpack 寻找模块时应该从哪些路径查找, resolve.modules 的默认值就是 ["node_modules"], 我写成这样 modules: [APP_PATH] 就不去 "node_modules" 查找了.
resolve.modules 里的路径可以是相对路径, 也可以是绝对路径. 如果是相对路径, 查找模块时会像 node 查找模块一样, 先从离的最近的 node_modules 目录里查找, 如果没找到, 层层向上继续找, 直到到最外层的根目录的 node_modules. 如果是绝对路径, 就简单多了, 只在指定的路径里查找.