amosq
amosq

Reputation: 111

Webpack/ts-loader import with .js extension not resolving

My directory structure is as follows:

projectRoot
├── project-server
│   ├── src
│   └── pom.xml
├── project-ui
│   ├── tsconfig.json
│   └── src
│       └── file.ts.  (imports ./file.js)

My problem is that project-server uses the transpiled js files and such needs the .js extension to resolve the files. I'm using webpack-dev-server for development and using ts-loader but I'm getting the error that:

Module not found: Error: Can't resolve './file.js' in 
'/projectRoot/project-ui/src'

The following is my webpack.config.js :

module.exports = {
  entry: './project-ui/src/file1.ts',
  mode: "development",
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      ... other rules
    ]
  },
  resolve: {
    extensions: ['.js', '.ts'],
  }

My tsconfig.json has configuration specific to where project-server needs the js files. Namely, "outDir": "../project-server/src/main/resources/static"

So I'm unsure how to configure Webpack/ts-loader to correctly resolve the import statement.

Upvotes: 6

Views: 3868

Answers (2)

Brooke Hart
Brooke Hart

Reputation: 4059

Update as of 2022-10-20

Webpack v5.74.0 was released in July 2022, and it includes a new resolve.extensionAlias option which provides a solution to this problem.

For example:

resolve: {
    extensionAlias: {
        '.js': ['.js', '.ts'],
    },
}

Answer as at 2021-09-01

I'm dealing with basically the same issue at the moment. I'm afraid I don't have a good answer for you, though I have found a discussion from 2017 that said ts-loader doesn't support this behaviour:

https://github.com/microsoft/TypeScript/issues/16577#issuecomment-343649391

If support has been added since then, I haven't been able to find any details on it yet.

I have had some success though with setting up aliases in my webpack.config.js's resolve.alias section, so relative paths to certain files using .js are resolved by Webpack to the .ts equivalents. For example:

alias: {
    './file-processing.js': './file-processing.ts',
},

But this is a very clunky solution that's not at all scalable.

Upvotes: 12

amosq
amosq

Reputation: 111

ts-loader doesn't natively support having imports with a .js extension so this project https://github.com/softwareventures/resolve-typescript-plugin provides the extra step required to make this work.

Upvotes: 4

Related Questions