javascript - 将 Typescript 添加到现有的 React、Webpack 和 Babel 项目中

标签 javascript typescript webpack

我正在尝试将 Typescript 添加到当前的 React、Webpack 和 Babel 项目中。我希望能够在我的项目中支持诸如 [.js, .ts, .tsx] 之类的文件类型,因为我想成功迁移到 Typescript。

我已经取得了一些进展,但目前我无法解决此错误:

enter image description here

我也不能 100% 确定是否需要保留 Babel,或者是否可以在设置完成后将其删除。

我的tsconfig.json看起来像这样:

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es6", "dom", "esnext.asynciterable", "es2015"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        // "noEmit": true,
        "strictNullChecks": true,
        // "noImplicitAny": false,
        "jsx": "preserve"
    },
    "include": ["src"],
    "exclude": ["node_modules", "build", "scripts", "jest"]
}

我的 webpack.conf.js 在这里:https://gist.github.com/Martinnord/981769791c3e5e3a261af459b81f2733

由于我陷入困境,因此非常感谢所有帮助。

谢谢!

最佳答案

webpack.config.js 示例:

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/dist/',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      { test: /\.tsx?$/, loader: 'ts-loader' },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx', '.ts', '.tsx'],
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  devServer: {
    contentBase: path.resolve(__dirname, './dist'),
    hot: true,
  },
}

另外,在 tsconfig 中:

{
  ...
  "jsx": "react",
  ...
}

全文:here

关于javascript - 将 Typescript 添加到现有的 React、Webpack 和 Babel 项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57077433/

相关文章:

javascript - 定义我自己的 React 事件类型

javascript - Promise.resolve() 什么时候触发 then() 方法?

javascript - backbone.js 在脚本中找不到错误

javascript - requirejs - 在定义时构建模块,而不是在需要时构建模块

d3.js - D3.js 组件中的样式不以 Angular 2 显示

typescript - 使用 TypeScript 和 webpack 在项目之间共享代码

javascript - Odoo 搜索多个名称使用 OR 运算符

reactjs - 错误 TS2339 : Property 'for' does not exist on type 'HTMLProps<HTMLLabelElement>'

angular - 从映射生成类型/接口(interface)列表

javascript - 如何使用 create-react-app 创建新项目