我正在尝试导入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.
看起来错误回到打字稿不能解析文件,但我无法弄清楚为什么它找不到它。
事实证明,我需要为.gif扩展添加一个定义。
创建typings.d.ts
:
declare module "*.gif";
固定它。
如果您依赖typescript paths
功能,则需要使用能够正确解析路径的tsconfig-paths-webpack-plugin
。只需将其添加到您的webpack配置中即可
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
...
resolve: {
plugins: [new TsconfigPathsPlugin({ /*configFile: "./path/to/tsconfig.json" */ })]
}
...
}