2017-01-25 57 views
1

出於某種原因,我yarn run dev命令到後續失敗的原因:意外標記 - 的WebPack 2.2.0和SCSS

SyntaxError: /src/components/home/index.scss:Unexpected token (1:0) 
> 1 | .home { 
... 

我使用的WebPack 2.2.0這是設置像這樣:

module: { 
    rules: [ 
     { 
      test: /\.(js|jsx)$/, 
      use: 'babel-loader', 
      include: path.resolve(__dirname, 'src'), 
     }, { 
      test: /\.(scss)/, 
      include: path.resolve(__dirname, 'src'), 
      use: [ 
       'style-loader', 
       'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]', 
       'sass-loader', 
       { 
        loader: 'postcss-loader', 
        options: { 
         plugins: function() { 
          return [ 
           require('autoprefixer') 
          ] 
         } 
        } 
       } 
      ], 
      include: path.resolve(__dirname, 'src') 
     } 
    ] 
} 

而我在我的index.js組件中做的全部是import s from './styles.scss'。如果我刪除import語句並允許應用程序啓動,然後在應用程序運行時將import語句重新插入並刷新頁面,則樣式存在...我覺得這非常奇怪,並且以前沒有遇到此問題...

+0

守ldn't'sass-loader'來到loader數組的末尾? –

回答

1

thread解釋了爲什麼您收到此錯誤的原因:

I think I found out why it didn't work on the first place. Though Webpack allows requiring static assets on the client side, babel, which compiles the server code, fails to do so as on the server side Node's require understands only JS files. This means that server side rendering is not possible with the default Webpack and babel.

有幾種解決方案來解決這個問題,或多或少複雜到位。

最簡單的一個,是在服務器上忽略.scss像這樣:

我添加了一個運行server.js文件到項目

require('babel-core/register')({ 
    presets: ['es2015-node5', 'stage-0'], 
    plugins: ['transform-decorators-legacy'] //was needed to support decorators 
}) 

require.extensions['.scss'] =() => { 
    return; 
} 

require.extensions['.css'] =() => { 
    return; 
} 

require('./server') 

運行以代替:

"cross-env NODE_ENV=development node ./run-server.js" 

添加到項目中:

npm install babel-preset-es2015-node5 babel-plugin-transform-decorators-legacy -D 
+0

將你的模塊對象複製並粘貼到我的webpack.config.js文件中,並得到相同的錯誤...奇怪的是F. – leaksterrr

+0

你有一個簡單的repo,可以測試它嗎? –

+0

它還沒有在回購呢(這將是一個樣板)這裏有一個保管箱鏈接:https://www.dropbox.com/s/9lyqm8dki1j2yfb/Archive.zip?dl=0 – leaksterrr