【发布时间】:2017-07-15 17:41:52
【问题描述】:
我正在尝试创建我的第一个 Angular2 项目,但遇到了一件非常愚蠢的事情。我正在使用:
"@angular/common": "^2.3.1",
"webpack": "^2.2.1",
"extract-text-webpack-plugin": "^2.0.0-rc.2",
webpack.config 内容:
module.exports = {
devtool: "source-map",
entry: { 'polyfills': './angularApp/polyfills.ts', 'vendor': './angularApp/vendor.ts', 'app': './angularApp/main.ts'},
output: { path: __dirname + '/wwwroot/', filename: 'dist/[name].bundle.js', chunkFilename: 'dist/[id].chunk.js', publicPath: '/' },
resolve: { extensions: ['.ts', '.js', '.json'] },
devServer: { historyApiFallback: true, contentBase: path.join(__dirname, '/wwwroot/'), watchOptions: { aggregateTimeout: 300, poll: 1000 }},
module: {
rules: [
{ test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] },
{ test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: { loader: "css-loader", options: { sourceMap: true }} }) }
],
exprContextCritical: false
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'] }),
new CleanWebpackPlugin(['./wwwroot/dist', './wwwroot/assets']),
new ExtractTextPlugin({ filename: '[name].css', allChunks: true }),
new HtmlWebpackPlugin({ filename: 'index.html', inject: 'body', template: 'angularApp/index.html' }),
]
};
应用 HTML 中的组件引用:
<div class='col-sm-3'>
<navigation></navigation>
</div>
navigation.component.css 内容:
li.link-active a,
li.link-active a:hover,
li.link-active a:focus {
background-color: #4189C7;
color: white;
}
最后是 navigation.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css'.toString()]
})
export class NavigationComponent { }
问题:
构建运行没有任何错误,但组件样式是全局应用的,并不特定于组件。检查 HTML 我注意到标签上有唯一标识符,但 CSS 上没有。 但是,如果我像这样放置 css
//styleUrls: ['./navigation.component.css']
styles: [`
li.link-active a,
li.link-active a:hover,
li.link-active a:focus {
background-color: #4189C7;
color: white;
}`]
样式仅按预期应用于组件并接收唯一标识符。问题是项目范围的,所以我怀疑配置中有错误。老实说,我完全迷失了,并且在这上面花了很多时间,我确信我错过了一些明显的东西。
在你为组件中的 .toString() 部分抨击我之前,请注意,如果我删除它,我会在控制台中收到以下错误“预期'样式'是一个字符串数组”(这是我的第二个问题)
【问题讨论】:
-
使用您的选择器导航{ .. 您的风格 }
-
你的答案似乎很模糊。你能详细说明一下吗?如果我在 css 中使用选择器,它将破坏为组件创建单独代码的整个目的。
-
我会把你链接到这可能是一个很好的参考:github.com/AngularClass/angular2-webpack-starter/blob/master/… 在我之前的评论中,我建议你用选择器包装你的 css,这样样式就只有每个组件是唯一的。我似乎不明白你怎么说它完全相反
-
非常感谢。这为我指明了正确的方向。 webpack 配置错误,所以我使用了建议的模板。
标签: javascript css angularjs angular webpack