简体   繁体   中英

Typescript module import spits path in a string form instead of module

Trying to import method from typescript (.ts) file and instead of accessible method am getting path to virtual file (using webpack-dev-server ) transpiled by ts-loader in webpack.

App has been bootstraped using react-create-app (not using Typescript from the beginning) and am trying to introduce TS now.

constants/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;
};

Above console.log output:

“/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

Pieces of configuration relative to the subject:

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
  }
};

Found a solution, thanks to @MattMcCutchen.

ts-loader should have been in oneOf section of my webpack config. I' ve also explicitly excluded '.tsx?$' from file-loader .

That did the job :)

One of possigle general answers to question:

  • "why am I getting string paths instead of modules"

is

  • "because some other loader is packaging your file before loader you want to use is getting to it"

Thanks for suggestions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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