我有两个反应项目:
使用
导入1到2编译时失败Module not found: Can't resolve 'ReactDOM'
组件项目的Webpack配置:
var path = require('path');
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'index.js'
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ test: /(\.css$)/, loaders: ['style-loader', 'css-loader'] },
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
externals: {
'react': 'commonjs react',
'react-dom': 'ReactDOM'
}
};
我尝试删除上面的externals
部分,以便捆绑ReactDOM,但这似乎也无法解决问题。理想情况下,React不需要捆绑。 ReactDOM不是组件项目中的导入。
组件项目的package.json:
{
"name": "component",
"version": "0.1.0",
"main": "build/index.js",
"dependencies": {
"react-grid-layout": "^0.16.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"semantic-ui-css": "^2.2.12",
"semantic-ui-react": "^0.75.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --watch",
"build": "webpack"
},
"devDependencies": {
"@types/react": "^16.0.20",
"@types/react-dom": "^16.0.2",
"@types/react-grid-layout": "^0.16.0",
"@types/react-redux": "^5.0.12",
"awesome-typescript-loader": "^3.3.0",
"react-dom": "^16.0.0",
"react": "^16.0.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.5.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"source-map-loader": "^0.2.3",
"style-loader": "^0.19.0",
"typescript": "^2.6.1",
"webpack": "^2.6.1",
"url-loader": "^0.6.2"
}
}
在我的测试项目中,我有
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Component from 'component'
如果删除对Component的依赖,测试项目构建正常。一旦我导入Component,完整的错误消息是:
./node_modules/component/build/index.js
Module not found: Can't resolve 'ReactDOM' in '/mnt/c/Users/a8345/ws/test/node_modules/component/build'
当我使用打字稿时,我安装了@ types / react-dom。如果我有import ReactDOM from 'react-dom'
我得到./src/index.tsx (2,8): error TS1192: Module '"/mnt/c/Users/a8345/ws/test/node_modules/@types/react-dom/index"' has no default export
.. import * as ReactDOM from 'react-dom'
在测试项目中正常工作,除非我尝试导入我自己的组件。
我怀疑这是一个构建问题而不是导入问题,我应该如何最好地配置它以确保组件使用主机项目中的ReactDOM而不是将其捆绑到组件中?
提前致谢
答案 0 :(得分:5)
尝试
externals: {
'react': {commonjs: 'react'},
'react-dom': {commonjs: 'react-dom'}
}
答案 1 :(得分:0)
Webpack无法解析.js文件。将此添加到您的webpack.config.js。
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
通过this answer。