При импорте import s from './index.module.scss'; через module появляется ошибка TS2307: Cannot find module './index.module.scss' or its corresponding type declarations.
webpack.config.js настраивался в ручную конфиг
const path = require('path');
const HTMLWebpackPlugins = require('html-webpack-plugin');
const NODE_ENV = process.env.NODE_ENV;
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '.css', '.scss'],
},
mode: NODE_ENV ? NODE_ENV : 'development',
entry: path.resolve(__dirname, 'src/index.ts'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
},
module: {
rules: [
{
test: /\.[tj]sx?$/,
exclude: /node_modules/,
use: ['ts-loader'],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-modules-typescript-loader?modules',
{
loader: 'css-loader',
options: {
modules: {
mode: 'local',
localIdentName: '[name]__[local]__[hash:base64:5]',
auto: /\.module\.\w+$/i,
},
},
},
'sass-loader',
],
},
],
},
plugins: [
new HTMLWebpackPlugins({
template: path.resolve(__dirname, 'public/index.html'),
}),
],
devServer: {
port: 3005,
open: true,
hot: true,
},
devtool: 'source-map',
};
tsconfig.json тоже все в ручную устанавливалось
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"plugins": [{ "name": "typescript-plugin-css-modules" }],
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */,
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
eslint настройки airbnb
module.exports = {
env: {
browser: true,
},
extends: ['airbnb', 'airbnb/hooks', 'react-app', 'prettier', 'prettier/react'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['prettier', 'react', '@typescript-eslint'],
rules: {
'@typescript-eslint/no-unused-vars': 'error',
'no-console': 'error',
'react/jsx-filename-extension': ['error', { extensions: ['.jsx', '.tsx', '.ts', '.js'] }],
'import/extensions': [
'error',
'ignorePackages',
{
ts: 'never',
tsx: 'never',
js: 'never',
jsx: 'never',
},
],
},
settings: {
'import/resolver': {
webpack: {
config: 'webpack.config.js',
},
},
},
};
В первом модуле, когда создовал тоже была ошибка, но после запуска yarn start создался index.module.scss.d.ts и ошибка пропала.
// This file is automatically generated.
// Please do not change this file!
interface CssExports {
'root': string;
}
export const cssExports: CssExports;
export default cssExports;
При запуске второго модуля опять появилась эта ошибка но уже ничего не собирается. Пробовал копировать настройки в index.module.scss.d.ts в новый модуль, но все равно не работает.
TypeScript в целом никак не смотрит на webpack. То есть webpack отвечает за различные loaders (какую программу для обработки каких файлов использовать), а TS смотрит на типы. SCSS и т.п. файлы - это не JS-файлы, которые TS мог бы просто так загрузить и разобраться что там за сущности и какие типы. Поэтому он и ругается, что не понимает что это вообще такое (хотя импортируется как JS). В таких случаях создают общий тип. К примеру в том же next-js тоже такое есть.
/// <reference types="node" />
// Extend the NodeJS namespace with Next.js-defined properties
declare namespace NodeJS {
interface Process {
readonly browser: boolean
}
interface ProcessEnv {
readonly NODE_ENV: 'development' | 'production' | 'test'
}
}
declare module '*.module.css' {
const classes: { readonly [key: string]: string }
export default classes
}
declare module '*.module.sass' {
const classes: { readonly [key: string]: string }
export default classes
}
declare module '*.module.scss' {
const classes: { readonly [key: string]: string }
export default classes
}
То есть он ТС-у говорит, что результат такого импорта будет объект с ключ-значение "строка-строка".
declare module '*.svg' {
const value: string
export default value
}
declare module '*.png' {
const value: string
export default value
}
declare module '*.jpg' {
const value: string
export default value
}
declare module '*.jpeg' {
const value: string
export default value
}
declare module '*.ico' {
const value: string
export default value
}
Попробуй у себя создать папку @types и в нем styles.d.ts и прописать
declare module '*.module.sass' {
const classes: { readonly [key: string]: string }
export default classes
}
declare module '*.module.scss' {
const classes: { readonly [key: string]: string }
export default classes
}
А то, что у тебя автоматически создавался файл index.module.scss.d.ts, то это вопрос уже к той программе, которую ты вызывал через yarn start. Она смотрит, что используется TS и сама прописывает нужное. Такое поведение и в нексте есть. Но просто так ничего ен будет создаваться.
К слову, потому я и говорю использовать мою уже готовую заготовку, чтобы не бегать и не настраивать все это самому. Но иногда мозги себе поломать тоже полезно.
Все ошибку нашел. Полезно понять в приниципе, как это все собирается, но адище с версиями еще то конечно.
Ну так в чем именно ошибка была?
Да хрен знает на втыкал куча еще новых настроек, откатил версии и вроде заработало.
Рука-лицо... Но так часто бывает.
Да я уже понял, хочешь устроить ад для своих мозгов научись программировать)
Нет, не научись, а начни учиться))
До научиться еще огого.
Да правилино начни учиться, надеюсь на каком-то этапе все-таки появится толерантность к такому количеству ошибок.