webpack + less

使用less需要安装 'style-loader','css-loader','less-loader' 三个loader。

安装之后在webpack.config.js配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
  entry: {//入口文件
    app: './src/index.js'
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  plugins:[
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
       title: 'Output Management'
    }),
  ],
  output: {//输出文件
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
         test: /\.(png|svg|jpg|gif)$/,
         use: [
           'file-loader'
         ]
      },
      {
         test: /\.(less|css)$/,
         use: [
           'style-loader',
           'css-loader',
           'less-loader'
         ]
      },
    ]
  }
};
View Code

执行命令,这个时候会发现样式写在页面<head>标签的里面。

 

如果样式少,这样看着还可以,但是多的话,还是外链的方式比较好,所以我们用 extract-text-webpack-plugin 来进行处理,先安装,接着继续修改配置。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
  entry: {//入口文件
    app: './src/index.js'
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  plugins:[
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
       title: 'Output Management'
    }),
    new ExtractTextPlugin({
      filename: 'index.css',
      disable: false,
      allChunks: true,
    }),
  ],
  output: {//输出文件
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
         test: /\.(png|svg|jpg|gif)$/,
         use: [
           'file-loader'
         ]
      },
      {
         test: /\.(less|css)$/,
         use: ExtractTextPlugin.extract({
          use:[ 'css-loader','less-loader'],
          fallback: 'style-loader',
        }),
      },
    ]
  }
};
View Code

这时候执行命令结束之后,就会达到我们想要的结果。

 

posted @ 2018-11-02 15:58  yue朔  阅读(373)  评论(0编辑  收藏  举报