zoukankan      html  css  js  c++  java
  • webpack--loader

    loader 用于对模块的源代码进行转换。loader 可以使你在 import 或"加载"模块时预处理文件。loader 可以将文件从不同的语言(如 TypeScript)转换为 JavaScript,或将内联图像转换为 data URL。loader 甚至允许你直接在 JavaScript 模块中 import CSS文件!

    现在我们来演示一下如何用 loader 来处理 CSS 文件。

    先准备好内容。

    src/app.css

    body { background: pink;
    }

    src/app.js

    import css from './app.css';
    
    console.log("hello world");

    如果你现在运行 webpack 命令,会提示错误

    意思就是说,默认情况下,webpack 处理不了 CSS 的东西。

    我们来处理这个问题。

    $ npm install --save-dev css-loader style-loader

    webpack.config.js:

    var HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: './src/app.js',
      output: {
        path: __dirname + '/dist',
        filename: 'app.bundle.js'
      },
      plugins: [new HtmlWebpackPlugin({
        template: './src/index.html',
        filename: 'index.html',
        minify: {
          collapseWhitespace: true,
        },
        hash: true,
      })],
      module: {
        rules: [
          {
            test: /.css$/,
            use: [ 'style-loader', 'css-loader' ]
          }
        ]
      }
    };

    再执行webpack,就会把css打包进js文件了

     如果不希望把css打包到js文件里,可以使用extract-text-webpack-plugin插件把css打包到指定的css文件中

    npm install --save-dev extract-text-webpack-plugin  
    旧版本已经不支持webpack4了,所以要使用以下命令:
    npm install extract-text-webpack-plugin@next

     webpack.config.js:


    var HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry:'./src/app.js', output:{ filename:'app.bundle.js' }, plugins: [ new HtmlWebpackPlugin( { minify:{ collapseWhitespace: false, }, hash: true } ), new ExtractTextPlugin({ filename: 'css/[name].css' //路径以及命名 }) ], module: { rules: [ { test: /.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }), exclude: /node_modules/, } ] } }

     

    生成的html类似于:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Webpack App</title>
      <meta name="viewport" content="width=device-width,initial-scale=1"><link href="css/main.css?5300da63334cc72d7813" rel="stylesheet"></head>
      <body>
      <script src="app.bundle.js?5300da63334cc72d7813"></script></body>
    </html>

    在dist/css下面会生成main.css

  • 相关阅读:
    LeetCode Best Time to Buy and Sell Stock
    LeetCode Scramble String
    LeetCode Search in Rotated Sorted Array II
    LeetCode Gas Station
    LeetCode Insertion Sort List
    LeetCode Maximal Rectangle
    Oracle procedure
    浏览器下载代码
    Shell check IP
    KVM- 存储池配置
  • 原文地址:https://www.cnblogs.com/cowboybusy/p/10425520.html
Copyright © 2011-2022 走看看