-->

Webpacker/Typescript can't resolve rails asset

2019-08-30 22:35发布

问题:

I'm trying to import a file that is in the rails asset pipeline and for some reason webpack can't find it.

Here is my tsconfig.json:

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "baseUrl": ".",
    "paths": {
      "@images/*": ["app/assets/images/*"],
    }
  },
  "exclude": [
    "**/*.spec.ts",
    "node_modules",
    "vendor",
    "public"
  ],
  "compileOnSave": false
}

Here is my config/webpack/environment.js:

const { environment } = require('@rails/webpacker')
const customConfig = require('./custom');
const typescript =  require('./loaders/typescript')
const fileLoader = require('./loaders/file');

environment.loaders.append('file', fileLoader)
environment.loaders.append('typescript', typescript)

// Merge custom config
environment.config.merge(customConfig);

module.exports = environment

My config/webpack/custom.js:

const path = require('path');

module.exports = {
  resolve: {
    alias: {
      '@src': path.resolve(__dirname, '..', '..', 'app/javascript'),
      '@images': path.resolve(__dirname, '..', '..', 'app/assets/images'),
      '@components': '@src/components',
      React: 'react',
      ReactDOM: 'react-dom'
    }
  }
};

import "@images/ajax-circle.gif"; in one of my typsecript files gives error 2307 (can't resolve module) and webpack-dev-server is unable to compile with the following error:

ERROR in /Users/brandoncc/dev/my_app/app/javascript/lib/store_management.ts
[tsl] ERROR in /Users/brandoncc/dev/my_app/app/javascript/lib/store_management.ts(1,24)
      TS2307: Cannot find module '@images/ajax-circle.gif'.
webpack: Failed to compile.

It looks like the error comes back to typescript not being able to resolve the file, but I can't figure out why it can't find it.

回答1:

It turns out that I needed to add a definition for the .gif extension.

Creating typings.d.ts with:

declare module "*.gif";

fixed it.



回答2:

If you are relying on typescript paths feature, you need to use tsconfig-paths-webpack-plugin that will resolve the path correctly. Just add that to your webpack config

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  ...
  resolve: {
    plugins: [new TsconfigPathsPlugin({ /*configFile: "./path/to/tsconfig.json" */ })]
  }
  ...
}