Reactjs 如何在React应用程序中导入我的typescript文件中的js模块(具有绝对路径)?
我正在我的React应用程序中集成typescript,它有大量的代码。我在React组件上应用了一些应用程序级HOC,如下所示:Reactjs 如何在React应用程序中导入我的typescript文件中的js模块(具有绝对路径)?,reactjs,typescript,webpack,Reactjs,Typescript,Webpack,我正在我的React应用程序中集成typescript,它有大量的代码。我在React组件上应用了一些应用程序级HOC,如下所示: import React from 'react'; import HOC1 from 'app/hocs/hoc1'; import compose from 'recompose/compose; class MyComponent from React.Component { ...component stuff... } export defa
import React from 'react';
import HOC1 from 'app/hocs/hoc1';
import compose from 'recompose/compose;
class MyComponent from React.Component {
...component stuff...
}
export default compose(HOC1())(MyComponent);
但现在我在应用程序中添加了typescript,无论何时导入
import HOC1 from 'app/hocs/hoc1';
上面说
TS2307: Cannot find module 'app/hocs/hoc1'.
我不想将类型定义添加到所有HOC中。解决方案是什么?为什么会出现这个错误
[EDIT]我也在tsconfig
中使用baseUrl
。我的文件夹结构是
/Project/configs/tsconfig
/Project/src/app/hocs
在tsconfig中,我通过文档给出了baseUrl
作为。/src
另一次编辑
我的网页包配置如下所示:
{
test: /\.(t|j)sx?$/,
loader: 'happypack/loader?id=jsx-without-proptypes',
include: [
path.resolve(__dirname),
path.resolve(__dirname, '../src'),
],
},
整个网页包配置看起来像
const config = {
context: path.resolve(__dirname, '../src'),
mode: NODE_ENV,
optimization: {
splitChunks: false,
nodeEnv: NODE_ENV,
minimize: false,
},
node: {
net: 'empty',
},
output: {
path: path.resolve(__dirname, '../build/public/assets'),
publicPath: '/assets/',
sourcePrefix: ' ',
pathinfo: DEBUG, //https://webpack.js.org/configuration/output/#output-pathinfo
},
module: {
noParse: [/html2canvas/],
rules: [
{
test: /\.tsx?$/,
enforce: 'pre',
use: { loader: 'awesome-typescript-loader' },
},
...shimLoaders,
...selectiveModulesLoader,
{
test: /\.(t|j)sx?$/,
loader: 'happypack/loader?id=jsx-without-proptypes',
include: [
path.resolve(__dirname),
path.resolve(__dirname, '../src'),
],
},
{
test: /\.jsx?$/,
loader: 'happypack/loader?id=jsx-without-lodash-plugin',
include: [
path.resolve(__dirname, '../src/app/modules/insights/'),
],
exclude: /node_modules/,
},
{
test: /\.jsx?$/,
loader: 'happypack/loader?id=jsx-with-proptypes',
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: [['env', { include: ['babel-plugin-transform-es2015-template-literals'] }]],
},
},
{
test: /\.css$/,
use: getCssLoaders({
pwd: PWD,
debug: DEBUG,
}),
},
...getScssRules(DEBUG, PWD),
{
test: /\.less$/,
use: [DEBUG ? 'css-loader' : 'css-loader?minimize', 'less-loader'],
},
{
test: /\.txt$/,
loader: 'raw-loader',
},
{
test: /\.svg$/,
loader: 'spr-svg-loader',
},
{
test: /\.(png|jpg|jpeg|gif)$/,
loader: 'url-loader',
query: {
name: DEBUG ? '[path][name].[ext]' : '[hash].[ext]', // ?[hash]
limit: 10000,
},
},
{
test: /\.(woff|woff2)$/,
loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/font-woff',
},
{
test: /\.(otf|ttf)$/,
loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/octet-stream',
},
{
test: /\.eot$/,
loader: 'url-loader?name=fonts/[name].[ext]&limit=65000&mimetype=application/vnd.ms-fontobject',
},
{
test: /\.(wav|mp3)$/,
loader: 'file-loader',
query: {
name: DEBUG ? '[path][name].[ext]' : '[hash].[ext]', // ?[hash]
},
},
{
test: /\.pug/,
loader: 'pug-loader',
},
{
test: /\.html$/,
include: /src\/app/,
loader: StringReplacePlugin.replace({
replacements: [
{
//Replaces ES6 strings from languagePack to simple string
pattern: /__\(\s*`([^`]*)`\s*\)/gi,
replacement: (match, p1) => {
let replacedStr = p1;
replacedStr = replacedStr.replace(new RegExp('\\$\\{([\\w\\.\\:\\-]+)\\}', 'g'), '\' + $1 + \'');
return `'${replacedStr}'`;
},
},
{
//Following methods - look out carefully for the *quotes* (single/double)
//doing what i18nPlugin would do for html files - with the *single* quotes
pattern: /__\(\s*'(.+?)'\s*\)/g,
replacement: (match, p1) => {
const replacedStr = p1;
return `'${replacedStr}'`;
},
},
{
//doing what i18nPlugin would do for html files - with the *double* quotes
pattern: /__\(\s*"(.+?)"\s*\)/g,
replacement: (match, p1) => {
const replacedStr = p1;
return `"${replacedStr}"`;
},
},
],
}),
},
],
},
resolve: {
modules: [
path.resolve(PWD),
path.resolve(PWD, '..'),
'node_modules',
'web_modules',
'src',
],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.webpack.js', '.web.js'],
alias: ALIAS,
// symlinks: false, //https://webpack.js.org/configuration/resolve/#resolve-symlinks, https://github.com/webpack/webpack/issues/1643
},
plugins: [getProvidePlugin(), getLoaderOptionPlugin({ debug: DEBUG }), ...getHappypackPlugin({ debug: DEBUG })],
resolveLoader: {
modules: ['node_modules', path.resolve(PWD, '../../node_modules'), path.resolve(PWD, './config/loaders/')],
alias: {
text: 'raw-loader', // treat text plugin as raw-loader
jst: 'ejs-loader',
style: 'style-loader',
imports: 'imports-loader',
},
},
bail: !DEBUG,
watch: DEBUG,
cache: DEBUG,
stats: DEBUG ?
{
colors: true,
reasons: false,
hash: VERBOSE,
version: VERBOSE,
timings: true,
chunks: false,
chunkModules: VERBOSE,
cached: VERBOSE,
cachedAssets: VERBOSE,
performance: true,
} :
{ all: false, assets: true, warnings: true, errors: true, errorDetails: false },
};
另一次编辑
上定义的别名也没有起作用。
使用别名
要将导入映射到正确的文件,您需要使用webpack配置中的config.resolve.alias
字段
在您的场景中,将出现以下情况:
const config = {
resolve: {
alias: {
'app': path.resolve(__dirname, 'src/app/'),
},
},
};
我不是100%确定我做得对,但我也在tsconfig中指定
路径
键,如下所示:
"baseUrl": "./src",
"paths": {
"@common/*": ["./common/*"],
"@moduleA/*": ["./moduleA/*"],
"@moduleB/*": ["./moduleB/*"],
}
而且似乎还可以
@
前缀只是我在tsconfig.json
中区分模块和npm依赖项的一种方法,你是否有“allowJs”:true
?此外,如果你要导入本地模块,你需要在路径中使用/
来指定,例如从“/app/hocs/HOC1”导入HOC1“允许“:true
在我的tsconfig中,没有任何方法可以代替导入所有内容,因为导入100个文件会使我在这里键入的内容相对混乱。我的代码中没有键入错误。@AjayGaur,它不编译吗?总是犯同样的错误?还是IDE是抱怨的对象?@AjayGaur,正如您在src
上定义的context
一样。如果config.resolve.alias
mapping'app':“../src/app'
有效,您能试试吗?我的tsconfig