如何防止babel在es2016项目中尝试转换资源(svg,css等)?
例如这个简单的项目:
src / app.js:
import logo from './logo.svg';
const Obj = { name: 'obj' };
export default Obj;
src / logo.svg :常规SVG可缩放矢量图形图像
package.json:
"name": "test-babel",
"version": "1.0.0",
"description": "Please babel do not try converting svg files to js",
"scripts": {
"dev": "cross-env NODE_ENV=development babel-watch --presets es2015 src/app.js"
},
...
没有.babelrc文件,没有webpack /没有捆绑包
编译会导致以下错误:
$ npm run dev
> test-import@1.0.0 dev /home/user/workspace/babel
> cross-env NODE_ENV=development babel-watch --presets es2015 src/app.js
/home/user/workspace/babel/src/logo.svg:1
(function (exports, require, module, __filename, __dirname) { <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
^
SyntaxError: Unexpected token <
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Module._extensions..js (module.js:663:10)
at babelWatchLoader (/home/user/workspace/babel/node_modules/babel-watch/runner.js:53:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/user/workspace/babel/node_modules/babel-watch/runner.js:62:7)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
答案 0 :(得分:1)
发现了此插件:https://www.npmjs.com/package/babel-plugin-inline-import
如果在.babelrc中声明了扩展名,则在编译时会内联导入的资源:
{
"plugins": [
["babel-plugin-inline-import", {
"extensions": [
".css",
".svg"
]
}]
]
}
这解决了我的问题。