首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >应用角4的光阑Webpack (SCSS)

应用角4的光阑Webpack (SCSS)
EN

Stack Overflow用户
提问于 2017-08-16 20:07:19
回答 2查看 3.3K关注 0票数 1

对不起,这是另一个webpack/scss/sass的问题。寻找答案让我头晕目眩,尤其是对webpack和角尚不熟悉。

我想使用sass/scss文件与我已经创建的使用VisualStudio2017 ASP.NET核心角项目模板创建的角4应用程序。

从盒子里出来,它会生成文件让你开始工作。我只想为app.component - app.component.scss创建一个新的scss文件。

我已经这样做了,并试图最好地猜测如何获得一些东西来操作scss文件。我完全不清楚什么是必需的。我看到网络上的大多数例子都使用了sass-loader,但是它们有不同的配置--这确实让我感到困惑。

所以我在这里发出了一个很大的求救信号。要让scss文件在我的场景中工作,我需要做什么?

以下是我所拥有的:

package.json

这是从Visual模板生成的初始文件:

代码语言:javascript
复制
{
  "name": "AngularShell_Web",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/animations": "4.2.5",
    "@angular/common": "4.2.5",
    "@angular/compiler": "4.2.5",
    "@angular/compiler-cli": "4.2.5",
    "@angular/core": "4.2.5",
    "@angular/forms": "4.2.5",
    "@angular/http": "4.2.5",
    "@angular/platform-browser": "4.2.5",
    "@angular/platform-browser-dynamic": "4.2.5",
    "@angular/platform-server": "4.2.5",
    "@angular/router": "4.2.5",
    "@ngtools/webpack": "1.5.0",
    "@types/webpack-env": "1.13.0",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.4.2",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.4.1",
    "url-loader": "0.5.9",
    "webpack": "2.5.1",
    "webpack-hot-middleware": "2.18.2",
    "webpack-merge": "4.1.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "chai": "4.0.2",
    "jasmine-core": "2.6.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3"
  }
}

我已经使用nodenpm install --save-dev安装了以下npm install --save模块

代码语言:javascript
复制
Module       | Version
---------    | -------
node-sass    | ^4.5.3 
sass-loader  | ^6.0.6
style-loader | https://registry.npmjs.org/style-loader/-/style-loader-0.18.2.tgz

注意:不太确定为什么样式加载程序版本是这样的。

app\components\app.component.html

代码语言:javascript
复制
<div class='container-fluid'>
    <div class='row'>
        <div class='col-sm-3'>
            <nav-menu></nav-menu>
        </div>
        <div class='col-sm-9 body-content'>
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

app\components\app.component.css

代码语言:javascript
复制
@media (max-width: 767px) {
    /* On small screens, the nav menu spans the full width of the screen. Leave a space for it. */
    .body-content {
        padding-top: 50px;
    }
}

app.component.ts

代码语言:javascript
复制
import { Component } from '@angular/core';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
}

webpack.config.js

这是我尝试的更改,以尝试加载sass:

代码语言:javascript
复制
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.scss$/, use: [ 'to-string-loader', isDevBuild ? 'sass-loader' : 'sass-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

webpack.config.vendor.js

代码语言:javascript
复制
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
    '@angular/animations',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    'zone.js',
];
const nonTreeShakableModules = [
    'bootstrap',
    'bootstrap/dist/css/bootstrap.css',
    'es6-promise',
    'es6-shim',
    'event-source-polyfill',
    'jquery',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: ['.js'] },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
            ]
        },
        output: {
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            // To keep development builds fast, include all vendor dependencies in the vendor bundle.
            // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
            vendor: isDevBuild ? allModules : nonTreeShakableModules
        },
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) },
                { test: /\.scss(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'sass-loader' : 'sass-loader?minimize' }) }
            ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        entry: { vendor: allModules.concat(['aspnet-prerendering']) },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2',
        },
        module: {
            rules: [
                    { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                    { test: /\.scss(\?|$)/, use: ['to-string-loader', isDevBuild ? 'sass-loader' : 'sass-loader?minimize'] }
            ]
        },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ]
    });

    return [clientBundleConfig, serverBundleConfig];
}

更新的app.component.ts

代码语言:javascript
复制
import { Component } from '@angular/core';

@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css', './app.component.scss']
})
export class AppComponent {
}

更新的app.component.html

现在已经有了类测试的范围,类测试在sass中定义:

代码语言:javascript
复制
<div class='container-fluid'>
    <div class='row'>
        <div class='col-sm-3'>
            <nav-menu></nav-menu>
        </div>
        <div class='col-sm-9 body-content'>
            <span class="test">Test</span>
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

最后,新的sass文件app.component.scss

我想在我的应用程序中使用这个。

代码语言:javascript
复制
.test {
    color: red;
}

运行应用程序(Visual F5)时,在Chrome中会出现以下错误:

代码语言:javascript
复制
NodeInvocationException: Prerendering failed because of error: Error: Module parse failed:       
G:\vs\AngularLearn\shell\src\AngularShell.Web\node_modules\sass-loader\lib\loader.js!     
G:\vs\AngularLearn\shell\src\AngularShell.Web\ClientApp\app\components\app\app.component.scss Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| .test {
| color: red; }
| 

这个question可能是相关的,但并没有给我所需要的信息--我仍然很困惑。

EN

回答 2

Stack Overflow用户

发布于 2017-10-04 18:34:08

看起来您的预录制失败了,这可能是有意义的,因为您在clientBundleConfig中有scss的规则,而不是serverBundleConfig。尝试将相同的规则添加到serverBundleConfig或共享中,就像我拥有的那样:

代码语言:javascript
复制
const sharedConfig = {
    stats: { modules: false },
    context: __dirname,
    resolve: { extensions: [ '.js', '.ts' ] },
    output: {
        filename: '[name].js',
        publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        rules: [
            { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
            { test: /\.html$/, use: 'html-loader?minimize=false' },
            { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
            {
                test: /\.scss$/,
                // exclude: /node_modules/,
                use: extractCSS.extract({
                    use: ['css-loader', 'sass-loader']
                })
            },
        ]
    },
    plugins: [new CheckerPlugin(), extractCSS]
};
票数 0
EN

Stack Overflow用户

发布于 2017-08-17 13:58:55

sass应该与webpack一起用角自动编译,只需在组件中放置一个.scss,我就可以编译了。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45722149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档