typescript 引入文件-如何在React应用程序中的typescript文件中导出js模块(带有绝对路径)

2023-08-29 0 7,025 百度已收录

如何在React应用程序中的typescript文件中导出js模块(带有绝对路径)? ¶

阿贾*_*aur12

我正在将 typescript 集成到我的 React 应用程序中,该应用程序有很多代码。 我有一些应用于 React 组件的应用程序级 HOC:

import React from 'react';
import HOC1 from 'app/hocs/hoc1';
import compose from 'recompose/compose;
class MyComponent from React.Component {
     ...component stuff...
}
export default compose(HOC1())(MyComponent);

但是现在我已经将打字稿添加到我的应用程序中typescript 引入文件typescript 引入文件,每当我导出时

import HOC1 from 'app/hocs/hoc1';

它说

TS2307: Cannot find module 'app/hocs/hoc1'.

我不想为所有 HOC 添加类型定义。 有哪些解决方案以及为什么会出现此错误?

[编辑] 我也在使用 baseUrl 的 tsconfig 。 我的文件夹结构是

/Project/configs/tsconfig
/Project/src/app/hocs

在 tsconfig 中,我已经通过文档将 baseUrl 指定为 ../src 。

另一个编辑和我的 webpack 配置如下所示:

    {
        test: /.(t|j)sx?$/,
        loader: 'happypack/loader?id=jsx-without-proptypes',
        include: [
          path.resolve(__dirname),
          path.resolve(__dirname, '../src'),
        ],
      },

整个 webpack 配置看起来像

const config = {
  context: path.resolve(__dirname, '../src'),
  mode: NODE_ENV,
  optimization: {
    splitChunks: false,
    nodeEnv: NODE_ENV,
    minimize: false,
  },
  node: {
    net: 'empty',
  },
  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    sourcePrefix: '  ',
    pathinfo: DEBUG, //https://webpack.js.org/configuration/output/#output-pathinfo
  },
  module: {
    noParse: [/html2canvas/],
    rules: [
      {
        test: /.tsx?$/,
        enforce: 'pre',
        use: { loader: 'awesome-typescript-loader' },
      },
      ...shimLoaders,
      ...selectiveModulesLoader,
      {
        test: /.(t|j)sx?$/,
        loader: 'happypack/loader?id=jsx-without-proptypes',
        include: [
          path.resolve(__dirname),
          path.resolve(__dirname, '../src'),
        ],
      },
      {
        test: /.jsx?$/,
        loader: 'happypack/loader?id=jsx-without-lodash-plugin',
        include: [
          path.resolve(__dirname, '../src/app/modules/insights/'),
        ],
        exclude: /node_modules/,
      },
      {
        test: /.jsx?$/,
        loader: 'happypack/loader?id=jsx-with-proptypes',
      },
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        query: {
          presets: [['env', { include: ['babel-plugin-transform-es2015-template-literals'] }]],
        },
      },
      {
        test: /.css$/,
        use: getCssLoaders({
          pwd: PWD,
          debug: DEBUG,
        }),
      },
      ...getScssRules(DEBUG, PWD),
      {
        test: /.less$/,
        use: [DEBUG ? 'css-loader' : 'css-loader?minimize', 'less-loader'],
      },
      {
        test: /.txt$/,
        loader: 'raw-loader',
      },
      {
        test: /.svg$/,
        loader: 'spr-svg-loader',
      },
      {
        test: /.(png|jpg|jpeg|gif)$/,
        loader: 'url-loader',
        query: {
          name: DEBUG ? '[path][name].[ext]' : '[hash].[ext]', // ?[hash]
          limit: 10000,
        },
      },
      {
        test: /.(woff|woff2)$/,
        loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/font-woff',
      },
      {
        test: /.(otf|ttf)$/,
        loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/octet-stream',
      },
      {
        test: /.eot$/,
        loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/vnd.ms-fontobject',
      },
      {
        test: /.(wav|mp3)$/,
        loader: 'file-loader',
        query: {
          name: DEBUG ? '[path][name].[ext]' : '[hash].[ext]', // ?[hash]
        },
      },
      {
        test: /.pug/,
        loader: 'pug-loader',
      },
      {
        test: /.html$/,
        include: /src/app/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              //Replaces ES6 strings from languagePack to simple string
              pattern: /__(s*`([^`]*)`s*)/gi,
              replacement: (match, p1) => {
                let replacedStr = p1;
                replacedStr = replacedStr.replace(new RegExp('\$\{([\w\.\:\-]+)\}', 'g'), '' + $1 + '');
                return `'${replacedStr}'`;
              },
            },
            {
              //Following methods - look out carefully for the *quotes* (single/double)
              //doing what i18nPlugin would do for html files - with the *single* quotes
              pattern: /__(s*'(.+?)'s*)/g,
              replacement: (match, p1) => {
                const replacedStr = p1;
                return `'${replacedStr}'`;
              },
            },
            {
              //doing what i18nPlugin would do for html files - with the *double* quotes
              pattern: /__(s*"(.+?)"s*)/g,
              replacement: (match, p1) => {
                const replacedStr = p1;
                return `"${replacedStr}"`;
              },
            },
          ],
        }),
      },
    ],
  },
  resolve: {
    modules: [
      path.resolve(PWD),
      path.resolve(PWD, '..'),
      'node_modules',
      'web_modules',
      'src',
    ],
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.webpack.js', '.web.js'],
    alias: ALIAS,
    // symlinks: false, //https://webpack.js.org/configuration/resolve/#resolve-symlinks, https://github.com/webpack/webpack/issues/1643
  },
  plugins: [getProvidePlugin(), getLoaderOptionPlugin({ debug: DEBUG }), ...getHappypackPlugin({ debug: DEBUG })],
  resolveLoader: {
    modules: ['node_modules', path.resolve(PWD, '../../node_modules'), path.resolve(PWD, './config/loaders/')],
    alias: {
      text: 'raw-loader', // treat text plugin as raw-loader
      jst: 'ejs-loader',
      style: 'style-loader',
      imports: 'imports-loader',
    },
  },
  bail: !DEBUG,
  watch: DEBUG,
  cache: DEBUG,
  stats: DEBUG ?
    {
      colors: true,
      reasons: false,
      hash: VERBOSE,
      version: VERBOSE,
      timings: true,
      chunks: false,
      chunkModules: VERBOSE,
      cached: VERBOSE,
      cachedAssets: VERBOSE,
      performance: true,
    } :
    { all: false, assets: true, warnings: true, errors: true, errorDetails: false },
};

另一位编辑

定义的别名也没有做到这一点。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 typescript typescript 引入文件-如何在React应用程序中的typescript文件中导出js模块(带有绝对路径) https://www.wkzy.net/game/171401.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务