Быстрый переход к проблемам импорта:
import style from "../sass/app.scss"
Работает при компиляции, не определен во время выполнения. Интерфейс TS правильно связан.
import * as style from "../sass/app.scss"
TS2339: Property 'x' does not exist on type
Не работает во время компиляции, но работает во время выполнения.
const styles = require("../sass/app.scss");
Работает хорошо, но я не хочу использовать CJS import.
Использование v4.41.5 веб-пакета.
devDependencies:
"devDependencies": {
...
"@types/node-sass": "4.11.0",
"@types/redux-thunk": "2.1.0",
"@babel/core": "7.8.3",
"@babel/preset-env": "7.8.3",
"@babel/preset-react": "7.8.3",
"babel-loader": "8.0.6",
"style-loader": "1.1.3",
"css-loader": "3.4.2",
"sass-loader": "8.0.2",
"css-modules-typescript-loader": "4.0.0",
"html-webpack-plugin": "3.2.0",
"node-sass": "4.13.1",
"webpack": "4.41.5",
"webpack-cli": "3.3.10",
"webpack-dev-server": "3.10.1",
...
}
webpack.config. js:
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.s[ac]ss$/,
use: [
// Creates `style` nodes from JS strings
{ loader: "style-loader" },
{ 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")
// Translates CSS into CommonJS
{ 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)
// Compiles Sass to CSS
{ loader: "sass-loader" },
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
}
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js', '.scss', '.css' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
port: 9000
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
]
};
декларации.d.ts:
declare module '*.scss' {
export const content: {[className: string]: string};
}
app.s css:
.x {
background-color: red;
}
сгенерированные приложения.s css .d.ts:
// This file is automatically generated.
// Please do not change this file!
interface CssExports {
'app': string;
}
export const cssExports: CssExports;
export default cssExports;