前言
我對 Webpack、Babel、Loaders 及其互動方式的了解幾乎為零。
問題描述
我開發了一個 Angular 組件庫,我最近將其遷移到了 Angular 12。我目前正在設定 Storybook 以獲取檔案。我想使用 Storybook 插件“@etchteam/storybook-addon-css-variables-theme”在不同的 CSS 樣式表之間切換。
通過這個插件的檔案,我發現了 webpack 加載器的語法,特別是對于延遲加載的樣式表,即
import test from "!!style-loader?injectType=lazyStyleTag!css-loader!./test.css"
但是,在瀏覽器控制臺中,我得到Unhandled Promise rejection: file.use is not a function.
截圖:瀏覽器控制臺
我發現,我的主要問題與故事書無關,因為即使是一個簡單的 css-loader 匯入 url 也會回傳一個純字串而不是一個物件。
我花了幾天時間分析這個問題,但我真的無能為力。
環境
- NodeJS 14.17.6
- 打字稿 4.3.x
- 角 12.2.10
- 網路包 5.50.0
- @babel/核心 7.14.8
- css 加載器 6.4.0
- postcss-loader 6.1.1
// tsconfig.json
// Please note: this part has been assembled from multiple files, it might contain typos...
{
"compilerOptions": {
"baseUrl": "./",
"module": "es2020",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"experimentalDecorators": true,
"target": "es2015",
"allowSyntheticDefaultImports": true,
"types": [
"node"
],
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}
再現
不幸的是,我無法使用例如 CodeSandbox 設定最小再現。但是我能夠使用新的 Angular 作業區在本地重現它:
$ npx -p @angular/cli@12 ng new css-loader-repro
$ npm i [email protected]
// /typings.d.ts
declare module "*.css";
// /tsconfig.app.json
// notice: i've added "typings.d.ts" to "files" array!
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts",
"typings.d.ts"
],
"include": [
"src/**/*.d.ts"
]
}
// /src/app/test.css
body {
background-color: red;
}
// /src/app/app.component.ts
import testCss from 'css-loader!./test.css';
console.log(testCss);
console.log('type of testCss: ', typeof testCss);
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'css-loader-repro';
}
我期望看到的
打開控制臺時,我希望testCss被列印為物件(見截圖)
我所看到的
的轉換結果css-loader作為string
(見截圖)回傳
限制
我不想提供自定義的 webpack 配置。對于實驗,這很好,但對于我的庫,我希望盡可能地接近 Angular 標準。
uj5u.com熱心網友回復:
@Akxe 解決了我的問題:將 css 檔案匯入 es6 回傳字串而不是物件
使用import * as test from '...'解決了我的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329307.html
標籤:有角的 网络包 css加载器 webpack-loader
