After configuring css-loader in webpack, an error require is not defined is reported in m browser.

recently I learned that webpack, has its own handwritten configuration, with no embellishment

.

a.css

body {background: red;}

main.js

require("./a.css"); 
function a(){}

package.json

{
  "name": "cssloader",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --mode development",
    "build": "webpack -p --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^0.28.11",
    "style-loader": "^0.21.0",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.14",
    "webpack-dev-server": "^3.1.3"
  }
}

webpack.config.js

module.exports = {
    entry: "./main.js",
    output: {
        filename: "bundle.js"
    },
    module: {
        rules: [
          {
            test: /\.css$/,
            use: [ "style-loader", "css-loader" ]
          }
        ]
    }
}

index.html

<html>
    <head>
        <!-- css  <link rel="stylesheet" href="./a.css"> -->
    </head>
<body>
    <h1>css-loader</h1>
    <script src="./main.js"></script>
</body>
</html>

execute npm run dev
the terminal did not report an error, but the browser reported an error

clipboard.png

clipboard.png
Why on earth is this? Save my rookie ~

Mar.04,2021

the JS you introduced in index.html is main.js . You can change this to bundle.js .
reason: think about why you need to use webpack to package main.js , because your browser does not support the modular way you write, so you need to use webpack for modular processing.


you don't seem to understand the webpack packaging process. After packaging, it is no longer a main.js. Main is just an entry file for webpack

.
Menu