【问题标题】:Compile CSS and JS in difference files / WEBPACK在不同的文件/WEBPACK 中编译 CSS 和 JS
【发布时间】:2020-11-27 16:36:55
【问题描述】:

两天来,我一直在尝试将 js 和 css 文件编译为单独的文件,因为现在一切都在一起了。有谁知道如何解决这个问题? 非常感谢您的帮助。

这是我的代码 webpack.config.js

const path = require('path');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'src/dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    {
                        loader: "css-loader",
                        options: {
                            url: false
                        }
                    },
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            },
        ]
    },
    plugins: [
        new BrowserSyncPlugin({
        // browse to http://localhost:3000/ during development,
        // ./public directory is being served
            host: 'localhost',
            port: 3000,
            files: ['./src/*.html'],
            server: { baseDir: ['src'] }
        }),
    
     new webpack.ProvidePlugin({
       $: 'jquery',
       jQuery: 'jquery'
     })
 
    ]
};

【问题讨论】:

标签: css webpack compilation jss


【解决方案1】:

我认为MiniCssExtractPlugin 是您正在寻找的。​​p>

它获取css-loader 的输出并创建 .css 包。它负责在浏览器中下载它们(通过在 webpack 运行时代码中推送一段代码),而且是的,它缩小了 .css :)。

简单用法:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  plugins: [new MiniCssExtractPlugin()],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

是的,你是对的。 Style-loader 创建 javascript sn-ps,稍后在运行时创建 .css 规则并将它们推送到浏览器全局 css 范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2017-08-16
    • 2019-01-23
    • 2018-01-30
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多