As a newcomer to webpack, I'm still grappling with how loaders interact with this tool. Consider the following TypeScript file index.ts
:
//index.ts
import "bootstrap/dist/css/bootstrap.css";
...
// typescript code
Accompanying this is the webpack configuration 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"] }
]
}
};
The process of webpack interacting with loaders, according to my understanding, goes as follows:
Step 1- Webpack encounters index.ts
, passes it to ts-loader
, which then reads and sends it to the ts compiler. The ts compiler generates a js code file index.js
, which is passed back to ts-loader
before being handed over to webpack.
Step 2- Upon reading index.js
, webpack needs to resolve the css file. It delegates this task to css-loader
, which interprets the css file as a string and hands off the job to style-loader
. The latter creates js code that can be injected into <style> tags in the index.html file.
Step 3- With bundle.js
prepared, the client requests index.html
, fetching the associated bundle.js
to introduce all css styles within <style> tags.
If my understanding is accurate, could you please clarify the following questions:
Q1- After style-loader
generates the js code, does it transmit this code back to
css-loader</code, and then onto webpack? Or does <code>style-loader
directly pass the generated js code to webpack?
Q2- Regarding the order in the webpack configuration file:
...
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
...
It appears that style-loader
precedes css-loader
(I tested this approach successfully, although unsure why). Shouldn't css-loader
initiate its work before style-loader
as shown below:
...
{ test: /\.css$/, use: ["css-loader", "style-loader"] }
...