问题
I'm struggling to get Webpack 4.0 to compile my SASS which I want to use Google material design SASS files with. I think it is an issue with not being able to access the SASS files in the node_modules folder.
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'
})
]
}
I thought by using:
include: path.resolve(__dirname, 'node_modules/@material'),
Would enable webpack to pick up the Material SASS files. but I get the error:
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";
Appreciate any help to be able to include the Google material SASS folder.
回答1:
As Mentioned in the Google Material Design docs, you need to use custom importer to load all material files as shown below.
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 };
}
then Update sass-loader with below
{
loader: 'sass-loader',
options: {
importer: materialImporter
},
}
来源:https://stackoverflow.com/questions/50044871/setting-up-webpack-4-0-to-use-google-material-design-sass-with-extracttextplugin