繁体   English   中英

Typescript模块以字符串形式而不是模块导入导入路径

[英]Typescript module import spits path in a string form instead of module

试图从打字稿(.ts)文件中导入方法,而不是从可访问的方法中获取通过webpack-dev-server ts-loader转换为虚拟文件(使用webpack-dev-server )的路径。

应用已使用react-create-app (从一开始就没有使用Typescript)进行引导,现在尝试引入TS。

常量/ dates.ts:

export const MINUTE_IN_MILLIS = 60 * 1000;
export const HOUR_IN_MILLIS = 60 * 60 * 1000;
export const DAY_IN_MILLIS = 24 * HOUR_IN_MILLIS;
export const WEEK_IN_MILLIS = 7 * DAY_IN_MILLIS;
export const NUMBER_OF_QUARTERS = 24 * 4;
export const WEEK_DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
export const US_TIMEZONES = [
  "America/Adak",
  "America/Anchorage",
  "America/Atka",
  "America/Boise",
   ...
];

somefile.js

import * as dates from "constants/dates";

export const substractUTCOffset = (date: Date) => new Date()
export const addUTCOffset = (date: Date) => new Date()

export const isUSTimeZone = (timezone: string) => {
  =======> console.log(dates); <=======
  return dates.US_TIMEZONES.indexOf(timezone) !== -1;
};

以上console.log输出:

“/static/media/dates.92294b02.ts"

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./react/src",
    // "outDir": "./build",
    "module": "esnext",
    "target": "es5",
    "lib": ["es5", "es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    // "rootDir": "./",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "importHelpers": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

webpack.dev.js

相对于主题的一些配置:

extensions: [".ts", ".tsx", ".web.js", ".js", ".json", ".web.jsx", ".jsx"]

 module: {
    strictExportPresence: true,
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" },

 alias: {
      constants: path.resolve(paths.appSrc, "constants/"),
    },

"use strict";

const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const WatchMissingNodeModulesPlugin = require("react-dev-utils/WatchMissingNodeModulesPlugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const getClientEnvironment = require("./env");
const paths = require("./paths");

const publicPath = "/";
const publicUrl = "";
const env = getClientEnvironment(publicUrl);

module.exports = {
  devtool: "cheap-module-source-map",
  entry: [
    require.resolve("./polyfills"),
    require.resolve("react-dev-utils/webpackHotDevClient"),
    paths.appIndexJs
  ],
  output: {
    path: paths.appBuild,
    pathinfo: true,

    filename: "static/js/bundle.js",
    chunkFilename: "static/js/[name].chunk.js",
    publicPath: publicPath,
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
  },
  resolve: {
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    extensions: [".ts", ".tsx", ".web.js", ".js", ".json", ".web.jsx", ".jsx"],
    alias: {
      components: path.resolve(paths.appSrc, "components/"),
      containers: path.resolve(paths.appSrc, "containers/"),
      constants: path.resolve(paths.appSrc, "constants/"),
      icons: path.resolve(paths.appSrc, "icons/"),
      models: path.resolve(paths.appSrc, "models/"),
      styles: path.resolve(paths.appSrc, "styles/"),
      utils: path.resolve(paths.appSrc, "utils/"),
      stores: path.resolve(paths.appSrc, "stores/")
    },
    plugins: [
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
    ]
  },
  module: {
    strictExportPresence: true,
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" },
      {
        test: /\.(js|jsx)$/,
        enforce: "pre",
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve("eslint")
            },
            loader: require.resolve("eslint-loader")
          }
        ],
        include: paths.appSrc
      },
      {
        oneOf: [
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve("url-loader"),
            options: {
              limit: 10000,
              name: "static/media/[name].[hash:8].[ext]"
            }
          },
          {
            test: /\.(js|jsx)$/,
            include: paths.appSrc,
            loader: require.resolve("babel-loader"),
            options: {
              cacheDirectory: true
            }
          },
          {
            test: /\.scss$/,
            use: [
              require.resolve("style-loader"),
              {
                loader: require.resolve("css-loader"),
                options: {
                  importLoaders: 1,
                  modules: true,
                  localIdentName: "[name]__[local]___[hash:base64:5]"
                }
              },
              {
                loader: require.resolve("postcss-loader"),
                options: {
                  ident: "postcss",
                  plugins: () => [
                    require("postcss-flexbugs-fixes"),
                    autoprefixer({
                      browsers: [
                        ">1%",
                        "last 4 versions",
                        "Firefox ESR",
                        "not ie < 9" // React doesn't support IE8 anyway
                      ],
                      flexbox: "no-2009",
                      grid: true
                    })
                  ]
                }
              },
              {
                loader: require.resolve("sass-loader")
              }
            ]
          },
          {
            test: /\.css$/,
            use: [
              require.resolve("style-loader"),
              {
                loader: require.resolve("css-loader"),
                options: {
                  importLoaders: 1
                }
              }
            ]
          },
          {
            test: /\.svg$/,
            loader: require.resolve("svg-react-loader")
          },
          {
            exclude: [/\.tsx?$/, /\.js$/, /\.html$/, /\.cshtml$/, /\.json$/],
            loader: require.resolve("file-loader"),
            options: {
              name: "static/media/[name].[hash:8].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new InterpolateHtmlPlugin(env.raw),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml
    }),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin(env.stringified),
    new webpack.HotModuleReplacementPlugin(),        
    new CaseSensitivePathsPlugin(),        
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),       
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ],

  node: {
    dgram: "empty",
    fs: "empty",
    net: "empty",
    tls: "empty",
    child_process: "empty"
  },

  performance: {
    hints: false
  }
};

感谢@MattMcCutchen,找到了一个解决方案。

ts-loader应该在我的webpack配置的oneOf部分中。 我还从file-loader明确排除了'.tsx?$'。

做到了:)

可能的一般性回答之一:

  • “为什么我得到字符串路径而不是模块”

  • “因为其他一些加载程序正在打包要使用的加载程序之前要打包的文件”

感谢您的建议!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM