意外的标记 。使用webpack导入.css文件时

时间:2017-08-03 23:59:36

标签: webpack webpack-dev-server

这是我的webpack配置

module: {
  loaders: [
    { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?' + JSON.stringify(babelLoaderQuery), 'eslint-loader']},
    { test: /\.json$/, loader: 'json-loader' },
    { test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
    { test: /\.css$/, loader: 'style!css?importLoaders=1!autoprefixer?browsers=last 2 version!sass' },

关闭的是,我有另一个项目,这是一个近乎副本,它工作正常。在这两种情况下,我都会像这样导入.css。

import 'react-day-picker/lib/style.css'

错误:

[require-hacker] Trying to load "style.css" as a "*.js"
[1] [piping] can't execute file: /Users/myUser/Projects/fed/bin/server.js
[1] [piping] error given was: /Users/myUser/Projects/fed/node_modules/react-day-picker/lib/style.css:3
[1] .DayPicker {
[1] ^
[1] 
[1] SyntaxError: Unexpected token .
[1]     at createScript (vm.js:74:10)
[1]     at Object.runInThisContext (vm.js:116:10)
[1]     at Module._compile (module.js:533:28)
[1]     at Module._extensions..js (module.js:580:10)
[1]     at require.extensions.(anonymous function) (/Users/myUser/Projects/fed/node_modules/babel-register/lib/node.js:152:7)
[1]     at Object._module2.default._extensions.(anonymous function) [as .js] (/Users/myUser/Projects/fed/node_modules/require-hacker/babel-transpiled-modules/require hacker.js:260:68)
[1]     at Module.load (module.js:503:32)
[1]     at tryModuleLoad (module.js:466:12)
[1]     at Module._load (module.js:458:3)
[1]     at Function.module._load (/Users/myUser/Projects/fed/node_modules/piping/lib/launcher.js:32:16)
[1] [piping] further repeats of this error will be suppressed...

2 个答案:

答案 0 :(得分:2)

这里有一些解决方法。在我的项目中,如果应用程序在浏览器窗口中运行,我使用is-in-browser模块来获取babel并仅导入外部样式表,您可以在组件中使用它,如下所示:

import isBrowser from 'is-in-browser';

if (isBrowser) {
    require ('react-day-picker/lib/style.css')
}

答案 1 :(得分:0)

可能是因为这个

{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?' + JSON.stringify(babelLoaderQuery), 'eslint-loader']},

这只会对.jsx文件进行联接并排除节点模块,您还需要为.js文件添加配置,并提及在运行加载程序时不要进入节点模块内部,这可以从堆栈跟踪中看到。

类似

{ test: /\.js?$/, exclude: /node_modules/, loaders: ['babel?' + JSON.stringify(babelLoaderQuery), 'eslint-loader']},

希望有所帮助:)