I'm new to webpack, still a little bit confused that how webpack cooperate with loaders. Let's we have below typescript file index.ts
:
//index.ts
import "bootstrap/dist/css/bootstrap.css";
...
// typescript code
and below is the webpack config file:
module.exports = {
mode: "development",
entry: "./src/index.ts",
output: { filename: "bundle.js" },
resolve: { extensions: [".ts", ".js", ".css"] },
module: {
rules: [
{ test: /\.ts/, use: "ts-loader", exclude: /node_modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
]
}
};
Below is my personal thought on how webpack works with loaders, please correct me if I'm wrong:
Step 1-Webpack encounter index.ts
, so it passes this file to ts-loader
, and ts-loader
read the file and pass it to ts compiler, ts compiler generates js code file index.js
and pass back to ts-loader
, then ts-loader
passes index.js
back to webpack.
Step 2- Webpack reads index.js
and needs to resolve the css file, so Webpack passes the task to css-loader
, so css-loader
reads the css file as a long long string, then passes the task to style-loader
, which creates js code that can be embedded in tags in the index.html file.
Step 3- bundle.js
is ready, and client sends a http request to get index.html
, and the bundle.js
is fetched and create a <style> tags to include all css styles.
Is my above understanding correct? If yes, below is my questions:
Q1-after style-loader
generates js code, does it pass those js code back to css-loader
, then css-loader
passes received js code to webpack? or style-loader
pass generated js code to webpack directly?
Q2- in the webpack config file:
...
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
...
it seems that the style-loader
is used first, then css-loader
steps in( I have tried this approach, it worked, not sure why it worked)
isn't that the css-loader
should start to work first then style-loader
as:
...
{ test: /\.css$/, use: ["css-loader", "style-loader"] }
...
Is my above understanding correct?
Yes
Q1-after style-loader generates js code, does it pass those js code back to css-loader, then css-loader passes received js code to webpack? or style-loader pass generated js code to webpack directly?
Answer: style-loader pass generated js code to webpack directly
Q2 it seems that the style-loader is used first, then css-loader steps in,
It can seem wrong. But its one of those things you need to read the docs for. The last thing to process it is mentioned at the top of the array. Personally I don't think the other way around would be any more intuitive.