我做了一些編輯,如下所列。
我正在使用 React (18.2.0)、Typescript (4.8.4) 和 Webpack (5.75.0) 的組合。我正在嘗試向我的應用程式添加一些樣式,并嘗試使用 CSS 模塊。我已經嘗試了一些 Webpack 配置,但沒有一個會導致 Webpack 使用正確的加載器。我已經嘗試了其他幾種加載器變體(如注釋掉的部分所示),但它們都不起作用。
我正在使用類似于此答案的方法來匯入樣式表(宣告 src/Globals.d.ts,為 tsc 設定 typescript-plugin-css-modules 編譯器插件,并匯入為import * as styles from './styles.module.css')
樣式表匯入
import * as styles from './ResultCount.module.css'
export const ResultCount = () => {
const orders = useSelector((state: ReducedState) => state.all.orders)
console.log('result count style name', styles.results) // always undefined
return <p className={styles.results}>
src/Globals.d.ts
declare module '*.module.css'
這是我得到的錯誤,無論我使用的加載器配置如何
cached modules 1.59 MiB (javascript) 27.4 KiB (runtime) [cached] 131 modules
./src/components/Order/styles.module.css 96 bytes [built] [1 error]
ERROR in ./src/components/Order/styles.module.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .order {
...
有人能告訴我我在 webpack.config.ts 檔案中做錯了什么嗎?
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true
},
exclude: /dist/
},
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
},
// {
// test: /\.css$/,
// include: path.join(__dirname, 'src/components'),
// loader: 'css-loader',
// //use: ['style-loader', 'css-loader']
// // use: [
// // 'style-loader',
// // {
// // loader: 'typings-for-css-modules-loader',
// // options: {
// // modules: true,
// // namedExport: true
// // },
// // },
// // 'css-loader',
// // ],
// },
]
},
編輯
我發現必須重新啟動 webpack serve 才能使這些更改生效(即使重新加載已打開)。新問題是:雖然 Webpack 成功構建,但任何匯入 .ts 檔案中的類都會回傳一個undefined. 所以沒有應用任何樣式。我更新了標題以反映新問題。
奇怪的是,我的語言服務器 (tsserver) 可以自動完成 .css 檔案中定義的類import * as styles from './styles.module.css',但是如果我在回傳 TSX 之前使用 console.log() 它,我總是會看到未定義的值。通過在瀏覽器檢查器中找到行內樣式,我已經確認損壞的 CSS 模塊名稱在最終呈現的頁面中。我也嘗試宣告一個 styles.module.css.d.ts 檔案(盡管由于 Typescript 插件我不需要宣告)以防萬一,但這仍然沒有解決問題。我也嘗試過(從這個答案)重命名 from styles.module.cssto<component name here>.module.css但這也沒有用。
有誰知道這可能是什么原因造成的?
uj5u.com熱心網友回復:
import * as styles from "module-path";在語意上不同于import styles from "module-path";. 基本上不要假設這些非 javascript 組成的模塊遵循任何高級模塊規則并始終默認匯入它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535382.html
