Webpacker/Typescript can't resolve rails asset pipeline file

房东的猫 提交于 2019-12-13 03:49:29

问题


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" */ })]
  }
  ...
}


来源:https://stackoverflow.com/questions/54880363/webpacker-typescript-cant-resolve-rails-asset-pipeline-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!