我尝试设置React with typescript,我遵循了教程here。我安装了react-select
,但当我尝试引用它时,我得到了一个编译器错误Build: Cannot find module 'react-select'
,如果我尝试从cmd行运行webpack,我得到了相同的错误。
我尝试按照建议包含以下加载程序作为github的修复程序,但我得到了同样的错误。
{
test: /\.js$/,
include: path.join(__dirname, 'node_modules', 'react-select'),
loader: 'jsx-loader',
}
有什么想法吗?
更新:
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"files": [
"./typings/index.d.ts",
"./src/components/Hello.tsx",
"./src/index.tsx"
]
}
package.json:
{
"name": "react-typescript-setup",
"version": "1.0.0",
"main": "./dist/bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack -w"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.3.1",
"react-dom": "^15.3.1",
"react-select": "^1.0.0-rc.1"
},
"devDependencies": {
"css-loader": "^0.25.0",
"react-select": "^1.0.0-rc.1",
"source-map-loader": "^0.1.5",
"style-loader": "^0.13.1",
"ts-loader": "^0.8.2",
"typings": "^1.3.3"
},
"description": ""
}
webpack.config.js
var path = require('path');
module.exports = {
entry: "./src/index.tsx",
output: {
path: __dirname,
filename: "./dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
debug: true,
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{ test: /\.tsx?$/, loader: "ts-loader" },
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ test: /\.js$/, loader: "source-map-loader" }
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
},
};
4条答案
按热度按时间vsaztqbk1#
首先你需要安装
react-select
的类型来导入它。一旦你完成了这个操作,就去到安装的类型并检查正在进行的导出类型。如果是类似
export = Select
的内容,则需要执行import = require('react-select')
如果它是类似
export default Select
的东西,你需要做import Select from
React选择'如果是命名导出,例如
export {Select}
,则需要执行import {Select} from 'react-select'
如果有多个命名导出,则必须显式导入每个导出或执行
import * as Select from 'react-select'
根据
react-select
的类型,如here所示,模块通过文件底部的默认导出来导出其内容。rxztt3cl2#
我正在查看我的软件包,发现
node_modules
中的@types
缺少react-select
软件包,因此我运行了此命令# npm install --save @types/react-select
,它解决了此问题。cl25kdpy3#
使用
webpack
配置Typsecript应定义如下:ts-loader
将Typescript加载到浏览器,source-map-loader
将源代码Map加载到浏览器,以便于调试。如果你需要什么或者我误解你了就告诉我。
crcmnpdw4#
我通过指向dist文件修复了它: