CSS/SCSS 모듈을 가져올 수 없습니다.TypeScript에 "모듈을 찾을 수 없습니다"라고 표시됨
CSS 모듈에서 테마를 Import하려고 하는데 TypeScript에서 "Cannot Find Module" 오류가 발생하여 실행 시 테마가 적용되지 않습니다.웹 팩 구성에 문제가 있는 것 같은데 어디가 문제인지 모르겠어요.
다음 도구를 사용하고 있습니다.
"typescript": "^2.0.3"
"webpack": "2.1.0-beta.25"
"webpack-dev-server": "^2.1.0-beta.9"
"react": "^15.4.0-rc.4"
"react-toolbox": "^1.2.3"
"node-sass": "^3.10.1"
"style-loader": "^0.13.1"
"css-loader": "^0.25.0"
"sass-loader": "^4.0.2"
"sass-lint": "^1.9.1"
"sasslint-webpack-plugin": "^1.0.4"
여기 제 것이 있습니다.webpack.config.js
var path = require('path');
var webpack = require('webpack');
var sassLintPlugin = require('sasslint-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index.tsx',
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:8080/',
filename: 'dist/bundle.js',
},
devtool: 'source-map',
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
},
module: {
rules: [{
test: /\.js$/,
loader: 'source-map-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loader: 'tslint-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loaders: [
'react-hot-loader/webpack',
'awesome-typescript-loader',
],
exclude: /node_modules/,
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}, {
test: /\.css$/,
loaders: ['style', 'css']
}],
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
plugins: [
new sassLintPlugin({
glob: 'src/**/*.s?(a|c)ss',
ignoreFiles: ['src/normalize.scss'],
failOnWarning: false, // Do it.
}),
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
contentBase: './'
},
};
그리고 나의App.tsxImport하려는 위치:
import * as React from 'react';
import { AppBar } from 'react-toolbox';
import appBarTheme from 'react-toolbox/components/app_bar/theme.scss'
// local ./theme.scss stylesheets aren't found either
interface IAppStateProps {
// No props yet
}
interface IAppDispatchProps {
// No state yet
}
class App extends React.Component<IAppStateProps & IAppDispatchProps, any> {
constructor(props: IAppStateProps & IAppDispatchProps) {
super(props);
}
public render() {
return (
<div className='wrapper'>
<AppBar title='My App Bar' theme={appBarTheme}>
</AppBar>
</div>
);
}
}
export default App;
typesafe 스타일시트 모듈 가져오기를 활성화하려면 무엇이 더 필요합니까?
TypeScript는 다음 이외의 파일이 있음을 인식하지 않습니다..ts또는.tsx따라서 Import에 알 수 없는 파일 접미사가 있으면 오류가 발생합니다.
다른 유형의 파일을 가져올 수 있는 웹 팩 구성이 있는 경우 이러한 파일이 존재함을 TypeScript 컴파일러에 알려야 합니다.이를 위해 적절한 이름을 가진 모듈을 선언하는 선언 파일을 추가합니다.
선언하는 모듈의 내용은 파일 유형에 사용되는 웹 팩로더에 따라 달라집니다.파이프가 연결된 웹 팩 구성에서는*.scsssass-module → css-module → style-module을 통한 파일은 Import된 모듈에 콘텐츠가 없으며 올바른 모듈 선언은 다음과 같습니다.
// declaration.d.ts
declare module '*.scss';
로더가 css-modules용으로 설정되어 있는 경우 선언을 다음과 같이 확장합니다.
// declaration.d.ts
declare module '*.scss' {
const content: Record<string, string>;
export default content;
}
다음은 나에게 맞는 완전한 구성입니다(같은 문제에 부딪힐 경우를 대비해 1시간 동안 시행착오를 반복했습니다).
TypeScript + WebPack + Sass
webpack.config.js
module.exports = {
//mode: "production",
mode: "development", devtool: "inline-source-map",
entry: [ "./src/app.tsx"/*main*/ ],
output: {
filename: "./bundle.js" // in /dist
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js", ".css", ".scss"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" },
{ test: /\.scss$/, use: [
{ loader: "style-loader" }, // to inject the result into the DOM as a style block
{ loader: "css-modules-typescript-loader"}, // to generate a .d.ts module next to the .scss file (also requires a declaration.d.ts with "declare modules '*.scss';" in it to tell TypeScript that "import styles from './styles.scss';" means to load the module "./styles.scss.d.td")
{ loader: "css-loader", options: { modules: true } }, // to convert the resulting CSS to Javascript to be bundled (modules:true to rename CSS classes in output to cryptic identifiers, except if wrapped in a :global(...) pseudo class)
{ loader: "sass-loader" }, // to convert SASS to CSS
// NOTE: The first build after adding/removing/renaming CSS classes fails, since the newly generated .d.ts typescript module is picked up only later
] },
]
}
};
또,declarations.d.ts프로젝트:
// We need to tell TypeScript that when we write "import styles from './styles.scss' we mean to load a module (to look for a './styles.scss.d.ts').
declare module '*.scss';
그리고 이 모든 것들이 당신의 집 안에 필요할 것입니다.package.json의 개발 의존성:
"devDependencies": {
"@types/node-sass": "^4.11.0",
"node-sass": "^4.12.0",
"css-loader": "^1.0.0",
"css-modules-typescript-loader": "^2.0.1",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"ts-loader": "^5.3.3",
"typescript": "^3.4.4",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.0"
}
그럼 너 그거 사야겠다.mystyle.d.ts네 옆에mystyle.scss정의한 CSS 클래스가 포함되어 있습니다.이 클래스는 Typescript 모듈로 Import하여 다음과 같이 사용할 수 있습니다.
import * as styles from './mystyles.scss';
const foo = <div className={styles.myClass}>FOO</div>;
CSS가 자동으로 로드됩니다(이때 CSS는style(사용자가 사용하지 않는 한) 페이지에서 스타일을 분리하기 위해 CSS 클래스 대신 암호화 식별자를 포함합니다.:global(.a-global-class) { ... }).
Import된 mystyles.d.ts는 이전 버전으로 컴파일 중에 생성된 새 버전이 아니기 때문에 CSS 클래스를 추가하거나 삭제 또는 이름을 변경할 때마다 첫 번째 컴파일이 실패합니다.다시 컴파일만 하세요.
즐거운 시간 되세요.
다음을 포함하는 typings.d.ts 파일을 추가합니다.
declare module "*.module.css";
css 파일은 반드시 'disclosed'로 선언해야 합니다.예를 들어 styles.css.
Import:
import React from 'react';
import styles from './styles.module.css';
typscript-plugin-css-modules를 사용하고 있습니다.
npm install -D typescript-plugin-css-modules
tsconfig.json
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
}
}
@Kalle에서 언급했듯이
TypeScript는 .ts 또는 .tsx 이외의 파일이 있는지 모르기 때문에 Import에 알 수 없는 파일서픽스가 있으면 오류가 발생합니다.
TS가 이 에러를 표시하지 않도록 하기 위해서, 타입 폴더를 작성하고, 내부에 선언을 포함한 확장 파일을 추가합니다.
다음과 같은 경우:
해서에 .d.ts 삭제
TypeScript type type type type type type type type type type type 。
.tsfiles는 유형과 실행 가능 코드가 포함된 구현 파일입니다.은 「」를 입니다..js보통 코드를 쓰는 장소입니다.
.d.ts파일생성되지 ..js출력은 형식 확인에만 사용됩니다.
TS 선언에 대한 자세한 내용은 여기를 참조하십시오.
ㅇㅇㅇㅇㅇㅇㅇ를 돼요.declaration.d.ts일일: :
declare module "*.module.css";
을 css " "로 하십시오..module.css.
Import:
import styles from './styles.module.css'
를 는, Sass 를 해 주세요..css「」가 붙은 .scss.
100% 동작
프로젝트에 "declarations.d.ts"를 추가하고 다음 행을 추가합니다.
declare module '*.css';
이것으로 충분합니다(Typescript + vite를 사용하고 있습니다.
을 에에
declaration.d.tsfolder (프로젝트 루트 폴더 내 파일)declare module "*.module.css"; declare module "*.module.scss";"declaration.d.ts"를 "include"에 추가하다
tsconfig.json.
{
"compilerOptions": {...},
"include": ["src", "declaration.d.ts"],
}
이 것에의, 언 the the the the the the the the 에서 하게 됩니다.src 입니다.root「」라고 하는 declarations.d.ts을 사용하다
해서 더하면 요.declaration.d.ts스타일을 직접 Import하는 폴더에 직접 저장하지만 이는 좋지 않은 방법입니다.
tsconfig.json 경로 설정을 사용하는 경우 경고
이러한 솔루션을 tsconfig 경로와 함께 사용하여 Import를 단축하는 경우 추가 설정이 필요합니다.
다음과 같은 경로 tsconfig를 사용하는 경우:
{
"compilerOptions": {
"paths": {
"style/*": [ "src/style/*" ],
}
}
}
다음과 같은 작업을 수행할 수 있습니다.
import { header } from 'style/ui.scss';
그런 다음 다음과 같이 웹 팩에 모듈 해결 구성도 추가해야 합니다.
module.exports = {
...
resolve: {
...
alias: {
style: path.resolve(__dirname, 'src', 'style')
}
}
}
패스가 설정에 따라서 설정되어 있는 것을 확인합니다.
이를 통해 웹 팩은 새로운 Import 경로가 실제로 모듈이라고 생각하기 때문에 기본적으로 node_modules 디렉토리가 되기 때문에 검색 위치를 알 수 있습니다.이 구성을 사용하면 검색 위치를 파악하고 검색하면 빌드가 작동합니다.
위의 답변은 기능하지 않았습니다.저는 sss + TS + Respect를 사용하고 있었습니다(이 답변은 고객님을 위한 것입니다).내가 한 일은:
src 폴더에 declarations.d.ts 파일을 만들고 그 파일에 다음 코드를 추가했습니다.
declare module "*.scss" {
const content: { [className: string]: string };
export = content;
}
그런 다음 src 폴더에 tsconfig.json 파일을 만들고 다음 코드를 추가했습니다.
{
"compilerOptions": {
"plugins": [{ "name": "typescript-plugin-css-modules" }]
},
//add the following
"include": ["src/**/*.ts", "declarations.d.ts"]
}
마지막으로 플러그인이 npm i typescript-css-css-discript로 설치되었습니다.
그리고 IT부문은 성공했습니다.
@Kalle이 전달한 답변에 따르면, 나는 또한 선언문의 오타를 검출할 수 있도록 할 필요가 있다는 것을 알았다.include 옵션 tsconfig "disconfig":
"include": ["./src/**/*.tsx", "./src/**/*.ts", "./typings/*.ts"]
★typingsdeclaration.d.ts@Kalle kal @ @ @ @ @ @ @ @ 。
나는 (적어도) 답을 찾았다.
여기저기서 많은 답변이 있었다:
// declaration.d.ts
declare module '*.scss';
네, 기존 .d.ts 파일로 했습니다.
// this.name.is.at.your.disposal.d.ts
export type {};
declare module "*.css";
declare global {
declare const NEXT_PUBLIC_SOME_URL: string;
}
그러나 ts 컴파일러는 여전히 "아, 이 blablabla를 이해할 수 없습니다."라고 불평했다.
그리고 이 대사가 눈에 띄었다.
export type {};
신의 이름이 무엇이든 간에 지워야 할 악이었어요
나는 지금 맥주를 사러 가야 한다.
제 프로젝트에서는 /src 폴더에 react-app-env.d.ts 파일이 있었습니다.
/// <reference types="react-scripts" />
왜 그랬는지 알 수가 없었지?Import처 검색을 검색했지만 검색 결과 0개가 표시되었습니다.그리고 어떻게 해서 삭제했더니 오류가 많이 났어요.
모듈 '.Home.scss' 또는 대응하는 형식 선언을 찾을 수 없습니다.TS2307 경고와 함께 컴파일되었습니다.
'.BlockPosts.module.css' 모듈 또는 대응하는 형식 선언을 찾을 수 없습니다.TS2307 경고와 함께 컴파일되었습니다.
그리고 나서 이 파일을 복원했고 모든 오류가 사라졌습니다.
프로젝트의 react-app-env.d.ts 폴더에 파일을 만듭니다.
/// <reference types="react-scripts" />
그리고 아마 너도 실수를 멈출거야
만 .react-app-env.d.ts에 "src dircory"라고./// <reference types="react-scripts" /> 하면 '다양한 이름'을 붙여서 문제를 할 수 .node_modules/react-scripts/lib/react-app.d.ts
제 경우 NodeJs의 (메이저)버전을 업그레이드했기 때문에 문제가 발생했을 가능성이 있습니다.프런트 엔드에서 다음과 같은 오류도 확인되었습니다.
Node Sass couldn't find a binding for your current environment
제 경우 해결 방법은 다음과 같습니다.
npm cache clean --forcenode_modulespackage-lock.jsonnpm install
후, 「」를 실행합니다.npm run dev결과, 다음과 같은 메시지가 나타납니다.
Failed to load C:\path\tsconfig.json: Missing baseUrl in compilerOptions
해결의 마지막 단계는 다음과 같습니다.
tsconfig.json및 add " " " 。"baseURL": ".",, 아래, 아래, 아래, 아래, 아래, 아래"compilerOptions":이렇게요.
"compilerOptions": {
"baseUrl": ".",
etc etc etc
이 시점에서 문제는 해결되었습니다.
레퍼런스:
노드 Sass가 현재 환경에 대한 바인딩을 찾을 수 없습니다.
제 경우 로더 scs와 sass를 코멘트하여 해결했습니다.
{
test: /\.css$/,
use:
[
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true
}
}
// ,
// {
// loader: 'sass-loader'
// }
// ,
// {
// loader: 'scss-loader'
// }
]
}
선언 모듈 ".module.css"는 결과에 영향을 주지 않았습니다.
기억: 항상 실행
npm start
이러한 설정 변경을 테스트하여 무슨 일이 발생했는지 확인합니다.**이렇게 하면 오늘 오후엔 도움이 될 거야
CRA로 만든 React 앱에서 react-app-env.d.ts를 추가해야 했습니다.
declare module '*.css';
위와 같이 declarations.d.ts에 이 선언을 추가하는 것은 기능하지 않았습니다.
하지만 나는 정확히 이 문제를 가지고 있었다.
typings.d.ts되었습니다.tsconfig.json되었습니다.- webpack 구성이 올바르게 구성되었습니다.
- 같은 셋업이 다른 프로젝트에서 동작하고 있었다.
그런데도 이 에러가 발생하고 있습니다.
도움이 된 것은 Import를 삭제한 것입니다.typings.d.ts
- import { Theme } from '@mui/material/styles'
그것은 오류나 경고를 전혀 주지 않았다.그러나 선언된 모듈이 제대로 작동하지 않았습니다.도움이 됐으면 좋겠다!
, 는 도도각 i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i를 하려고 했다.npm audit fix제 고민도 해결됐어요
언급URL : https://stackoverflow.com/questions/40382842/cant-import-css-scss-modules-typescript-says-cannot-find-module
'programing' 카테고리의 다른 글
| Spring Boot에서 로그백을 무효로 하다 (0) | 2023.03.06 |
|---|---|
| Onclick function "is not defined" (0) | 2023.03.06 |
| 테마 드롭다운 메뉴를 호버 대신 OnClick으로 설정하려고 합니다. (0) | 2023.03.06 |
| jersey2 클라이언트에서 응답으로 목록을 가져오는 방법 (0) | 2023.03.06 |
| Youtube 치수 워드프레스 (0) | 2023.03.06 |
