繁体   English   中英

webpack 样式加载器和 css 加载器不适用于简单示例

[英]webpack style loader and css loader not working for simple example

我试图按照这里的教程https://webpack.js.org/guides/asset-management/但是我永远无法加载 css 文件。 (文字从不红色)

https://github.com/bryandellinger/webpackassetmanagement

> --dist
> ----bundle.js
> ----index.html
> --src
> ----index.js
> ----style.css

webpack.config.js

const path = require('path');
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      },
       module: {
         rules: [
           {
             test: /\.css$/,
             use: [
               'style-loader',
               'css-loader'
             ]
           }
         ]
       }
    };

包.json

{
  "name": "webpack1",
  "version": "1.0.0",
  "description": "webpack tutorial",
  "private": true,
  "scripts": {
    "dev": "lite-server",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^1.0.0",
    "style-loader": "^0.22.1",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0"
  },
  "dependencies": {
    "lite-server": "^2.4.0",
    "lodash": "^4.17.10"
  }
}

索引.js

    import _ from 'lodash';

    function component() {
        let element = document.createElement('div');

        // Lodash, currently included via a script, is required for this line to work
        element.innerHTML = _.join(['Hello', 'webpack'], ' ');
        element.classList.add('hello'); 
        return element;
      }

      document.body.appendChild(component(

));

样式文件

.hello {
    color: red;
  }

索引.html

<!doctype html>
<html>
  <head>
    <title>Asset Management</title>
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

您需要在主 index.js 文件中导入 css 文件。 你可以通过添加import './style.css';来做到这一点import './style.css';

更新了 index.js

 import _ from 'lodash'; import './style.css'; function component() { let element = document.createElement('div'); // Lodash, currently included via a script, is required for this line to work element.innerHTML = _.join(['Hello', 'webpack'], ' '); element.classList.add('hello'); return element; } document.body.appendChild(component());

你忘记做的是在你的index.js导入你的style.css ,如果你不告诉 Webpack 它在那里,Webpack 不知道你的style.css

然后它会做的是从您导入的.css文件中收集所有 CSS,将其转换为字符串并将其传递给style-loader ,该style-loader将在index.html<head>中将其作为<style>输出.

因为你没有在入口点导入你的style.css ,Webpack 不知道它, css-loader不能从中收集 CSS 并且style-loader不能将它输出为<style> .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM