webpack2样式没法抽取出来?

发布于 2022-09-04 12:32:26 字数 4470 浏览 10 评论 0

"use strict";

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const CONFIG = require('./config');
var projectRoot = CONFIG.projectRoot || path.resolve(__dirname, '../');
var _ENV = CONFIG.env || 'dev';//prod

module.exports = {
    devtool: _ENV != 'prod' ? '#eval-source-map' : false,
    context: __dirname,//http://wxungang.github.io/1104/vue
    entry: {
        util: ['vue-router', path.join(projectRoot, './vue/service/service.js')],//需要抽离的业务工具类
        app: path.join(projectRoot, './vue/app.js'),
        page: path.join(projectRoot, './vue/page.js')
    },
    output: {
        path: path.join(projectRoot, './build/vue-' + _ENV),
        publicPath: '',//'./build/vue-'+_ENV+'/',//path.join(__dirname, '../src/build/dev/')
        filename: '[name].js',
        chunkFilename: 'chunks/[name].chunk.js',
        // crossOriginLoading: 'anonymous'
    },
    resolve: {
        alias: {
            'vue
: 'vue/dist/vue.common.js',
            'vue-router
: 'vue-router/dist/vue-router.common.js'
        },
        modules: ["node_modules"],
        mainFiles: ["index", "app"],
        extensions: [".js", ".json", '.vue']
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                        // the "scss" and "sass" values for the lang attribute to the right configs here.
                        // other preprocessors should work out of the box, no loader config like this nessessary.
                        'scss': 'vue-style-loader!css-loader!sass-loader',
                        'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
                        'less': 'vue-style-loader!css-loader!less-loader',
                        'css': ExtractTextPlugin.extract({
                            loader: 'css-loader',
                            fallbackLoader: 'vue-style-loader!css-loader!less-loader' // <- this is a dep of vue-loader, so no need to explicitly install if using npm3
                        })
                    }
                    //other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.less$/,
                loader: "style-loader!css-loader!less-loader"
            },
            {
                test: /\.scss$/,
                loaders: ["style-loader", "css-loader", "sass-loader"]
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            },
            {
                test: /\.html$/,
                loader: 'vue-html-loader'
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("style.css"),
        //注入一些全局变量
        new webpack.DefinePlugin({
            _ENV_: _ENV,
            _VERSION_: JSON.stringify("1.0.0")
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['util'],
            // (the commons chunk name)

            // filename: "vueCommons.js",
            // (the filename of the commons chunk)

            minChunks: Infinity,
            // (Modules must be shared between 3 entries)

            // chunks: ["pageA", "pageB"],
            // (Only use these entries)
            // children: true,
            // async: true,
        }),
        //可以和entry文件联合配置
        new HtmlWebpackPlugin({
            inject: false,
            title: 'vueJs of app',
            filename: 'app.html',
            template: '../vue/entry/template.ejs',
            scripts: ['./util.js', './app.js']
        }),
        new HtmlWebpackPlugin({
            inject: false,
            title: 'vueJs of page',
            filename: 'page.html',
            template: '../vue/entry/template.ejs',
            scripts: ['./util.js', './page.js']
        })
    ]
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

屌丝范 2022-09-11 12:32:26

官方文档描述如下:

ExtractTextPlugin generates a file per entry, so you must use [name], [id] or [contenthash] when using multiple entries.

所以每个 entry 只能抽取对应的单个文件,可以加上 [name], [id] or [contenthash] 如:new ExtractTextPlugin('[name].css')。其实很多由 gulp 或 grunt 转到 webpack 的都会感觉抽取 css 很麻烦,不过官方都是建议这样在 entry 中依赖 css 然后用 ExtractTextPlugin 抽取出来。不过下面这个简单的 hack 可以让 webpack 支持 entry 是 css 文件的:

class CssEntryPlugin {
  apply (compiler) {
    compiler.plugin('emit', (compilation, callback) => {
      compilation.chunks.filter(chunk => {
        return /\.css$/i.test(chunk.name);
      }).forEach(chunk => {
        const oldName = chunk.name;
        const newName = oldName.replace(/\.css$/i, '');

        chunk.files = chunk.files.filter(file => {
          const isCss = /\.css(|\.map)$/i.test(file);
          if (!isCss) {
            delete compilation.assets[file];
          }
          return isCss;
        }).map(oldFile => {
          // do not handle map file
          if (/\.map$/i.test(oldFile)) return oldFile;

          const newFile = oldFile.replace(oldName, newName);
          // change css assets name
          const tmp = compilation.assets[oldFile];
          compilation.assets[newFile] = tmp;
          delete compilation.assets[oldFile];
          return newFile;
        });
      });
      callback();
    });
  }
}

这样 entry 可以这么写:

{
  entry: {
    'index.css': './index.less'
  }
}

详情参考:https://github.com/d-band/doo...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文