我正在尝试导入位于Rails资产管道中的文件,由于某种原因,webpack找不到该文件。
这是我的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
}
这是我的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
我的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'
}
}
};
我的typsecript文件之一中的 import "@images/ajax-circle.gif";
给出错误2307(无法解析模块),并且webpack-dev-server
无法编译,并出现以下错误:
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.
看来错误归因于打字稿无法解析文件,但我不知道为什么找不到它。
答案 0 :(得分:0)
如果您依靠打字稿paths
功能,则需要使用tsconfig-paths-webpack-plugin
来正确解析路径。
只需将其添加到您的webpack配置中
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
...
resolve: {
plugins: [new TsconfigPathsPlugin({ /*configFile: "./path/to/tsconfig.json" */ })]
}
...
}
答案 1 :(得分:0)
原来,我需要为.gif扩展名添加一个定义。
使用以下方法创建typings.d.ts
:
declare module "*.gif";
修复了该问题。