3

我正在努力让 Webpack 4.0 编译我想使用 Google 材料设计 SASS 文件的 SASS。我认为这是无法访问 node_modules 文件夹中的 SASS 文件的问题。

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

module.exports = {
//entry: path.resolve(__dirname, 'react/test/index.js'),
entry: [path.resolve(__dirname, 'react/test/index.js'), 
path.resolve(__dirname, 'styles/main.scss')],
output: {
    path:path.resolve(__dirname, 'web/webroot/_ui/desktop//js'),
    filename: 'testOutput.js'
},
devtool: 'sourcemap',
watch: true,
module: {
    rules: [

        {
      test: /\.(css|sass|scss)$/,
                //exclude: /node_modules/,
                include: path.resolve(__dirname, 'node_modules/@material'),
                use:ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: ['css-loader','sass-loader'],
            })
        },
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: ['babel-loader']
        },
        {
            test: /\.css$/,
            exclude: /node_modules/,
            use: ['css-loader']
        }
    ]
},

plugins: [
    new ExtractTextPlugin({
        filename: 'style-soutput.css'
    })
]

}

我想通过使用:

包括:path.resolve(__dirname, 'node_modules/@material'),

将使 webpack 能够获取 Material SASS 文件。但我得到了错误:

Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.
@import 'themeColors';
@import "@material/button/mdc-button";

感谢能够包含 Google 材料 SASS 文件夹的任何帮助。

4

1 回答 1

2

正如 Google Material Design 文档中提到的,您需要使用自定义导入器来加载所有材料文件,如下所示。

const path = require("path");

function tryResolve_(url, sourceFilename) {
  // Put require.resolve in a try/catch to avoid node-sass failing with cryptic libsass errors
  // when the importer throws
  try {
    return require.resolve(url, { paths: [path.dirname(sourceFilename)] });
  } catch (e) {
    return "";
  }
}

function tryResolveScss(url, sourceFilename) {
  // Support omission of .scss and leading _
  const normalizedUrl = url.endsWith(".scss") ? url : `${url}.scss`;
  return (
    tryResolve_(normalizedUrl, sourceFilename) ||
    tryResolve_(
      path.join(
        path.dirname(normalizedUrl),
        `_${path.basename(normalizedUrl)}`
      ),
      sourceFilename
    )
  );
}

function materialImporter(url, prev) {
  if (url.startsWith("@material")) {
    const resolved = tryResolveScss(url, prev);
    return { file: resolved || url };
  }
  return { file: url };
}

然后用下面的更新 sass-loader

{
            loader: 'sass-loader',
            options: {
              importer: materialImporter
            },
          }
于 2019-07-07T21:59:39.777 回答